从Numpy数组创建Pandas DataFrame:如何指定索引列和列标题?
问题描述:
我有一个由列表列表组成的Numpy数组,代表一个带有行标签和列名的二维数组,如下所示:
I have a Numpy array consisting of a list of lists, representing a two-dimensional array with row labels and column names as shown below:
data = array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])
我希望生成的DataFrame具有Row1和Row2作为索引值,而Col1,Col2作为标头值
I'd like the resulting DataFrame to have Row1 and Row2 as index values, and Col1, Col2 as header values
我可以如下指定索引:
df = pd.DataFrame(data,index=data[:,0]),
但是我不确定如何最好地分配列标题.
however I am unsure how to best assign column headers.
答
You need to specify data
, index
and columns
to DataFrame
constructor, as in:
>>> pd.DataFrame(data=data[1:,1:], # values
... index=data[1:,0], # 1st column as index
... columns=data[0,1:]) # 1st row as the column names
编辑:如@joris注释中所示,您可能需要将上面的内容更改为np.int_(data[1:,1:])
才能获得正确的数据类型.
edit: as in the @joris comment, you may need to change above to np.int_(data[1:,1:])
to have correct data type.