Python 从 Numpy 数组创建 Pandas DataFrame:如何指定索引列和列标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20763012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?
提问by user3132783
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:
我有一个由列表列表组成的 Numpy 数组,代表一个二维数组,其中包含行标签和列名,如下所示:
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
我希望生成的 DataFrame 将 Row1 和 Row2 作为索引值,并将 Col1、Col2 作为标题值
I can specify the index as follows:
我可以按如下方式指定索引:
df = pd.DataFrame(data,index=data[:,0]),
however I am unsure how to best assign column headers.
但是我不确定如何最好地分配列标题。
采纳答案by behzad.nouri
You need to specify data, indexand columnsto DataFrameconstructor, as in:
您需要指定data,index并columns以DataFrame构造函数,如:
>>> 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.
编辑:在@joris 评论中,您可能需要更改上面的内容np.int_(data[1:,1:])以获得正确的数据类型。
回答by ryanjdillon
I agree with Joris; it seems like you should be doing this differently, like with numpy record arrays. Modifying "option 2" from this great answer, you could do it like this:
我同意乔里斯的观点;似乎您应该以不同的方式执行此操作,就像使用numpy record arrays 一样。从这个很好的答案中修改“选项 2” ,你可以这样做:
import pandas
import numpy
dtype = [('Col1','int32'), ('Col2','float32'), ('Col3','float32')]
values = numpy.zeros(20, dtype=dtype)
index = ['Row'+str(i) for i in range(1, len(values)+1)]
df = pandas.DataFrame(values, index=index)
回答by Jagannath Banerjee
Here is an easy to understand solution
这是一个易于理解的解决方案
import numpy as np
import pandas as pd
# Creating a 2 dimensional numpy array
>>> data = np.array([[5.8, 2.8], [6.0, 2.2]])
>>> print(data)
>>> data
array([[5.8, 2.8],
[6. , 2.2]])
# Creating pandas dataframe from numpy array
>>> dataset = pd.DataFrame({'Column1': data[:, 0], 'Column2': data[:, 1]})
>>> print(dataset)
Column1 Column2
0 5.8 2.8
1 6.0 2.2
回答by Aadil Srivastava
This can be done simply by using from_records of pandas DataFrame
这可以通过使用 Pandas DataFrame 的 from_records 来完成
import numpy as np
import pandas as pd
# Creating a numpy array
x = np.arange(1,10,1).reshape(-1,1)
dataframe = pd.DataFrame.from_records(x)
回答by javadba
Adding to @behzad.nouri 's answer - we can create a helper routine to handle this common scenario:
添加到@behzad.nouri 的答案 - 我们可以创建一个辅助程序来处理这种常见情况:
def csvDf(dat,**kwargs):
from numpy import array
data = array(dat)
if data is None or len(data)==0 or len(data[0])==0:
return None
else:
return pd.DataFrame(data[1:,1:],index=data[1:,0],columns=data[0,1:],**kwargs)
Let's try it out:
让我们试试看:
data = [['','a','b','c'],['row1','row1cola','row1colb','row1colc'],
['row2','row2cola','row2colb','row2colc'],['row3','row3cola','row3colb','row3colc']]
csvDf(data)
In [61]: csvDf(data)
Out[61]:
a b c
row1 row1cola row1colb row1colc
row2 row2cola row2colb row2colc
row3 row3cola row3colb row3colc


