从 Numpy 数组创建 Pandas DataFrame:如何指定索引列和列标题? [英] Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

查看:29
本文介绍了从 Numpy 数组创建 Pandas DataFrame:如何指定索引列和列标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由列表组成的 Numpy 数组,表示一个二维数组,其中包含行标签和列名,如下所示:

data = array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])

我希望生成的 DataFrame 将 Row1 和 Row2 作为索引值,将 Col1、Col2 作为标头值

我可以指定索引如下:

df = pd.DataFrame(data,index=data[:,0]),

但是我不确定如何最好地分配列标题.

解决方案

你需要指定dataindexcolumnsDataFrame 构造函数,如:

<预><代码>>>>pd.DataFrame(data=data[1:,1:], # 值... index=data[1:,0], # 第一列作为索引... columns=data[0,1:]) # 第一行作为列名

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆