从 Numpy 数组创建 Pandas DataFrame:如何指定索引列和列标题? [英] Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?
问题描述
我有一个由列表组成的 Numpy 数组,表示一个二维数组,其中包含行标签和列名,如下所示:
data = array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])
我希望生成的 DataFrame 将 Row1 和 Row2 作为索引值,将 Col1、Col2 作为标头值
我可以指定索引如下:
df = pd.DataFrame(data,index=data[:,0]),
但是我不确定如何最好地分配列标题.
你需要指定data
、index
和columns
到DataFrame
构造函数,如:
edit:如@joris 评论中一样,您可能需要将上面更改为 np.int_(data[1:,1:])
以获得正确的数据类型.
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]])
I'd like the resulting DataFrame to have Row1 and Row2 as index values, and Col1, Col2 as header values
I can specify the index as follows:
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
edit: as in the @joris comment, you may need to change above to np.int_(data[1:,1:])
to have correct data type.
这篇关于从 Numpy 数组创建 Pandas DataFrame:如何指定索引列和列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!