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

查看:1209
本文介绍了从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.

这篇关于从Numpy数组创建Pandas DataFrame:如何指定索引列和列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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