[英]What index should I use to convert a numpy array into a pandas dataframe?
I am trying to convert a simple numpy array into a pandas dataframe. 我试图将一个简单的numpy数组转换为pandas数据帧。
x
is my array, nam
is the list of the columns names. x
是我的数组, nam
是列名列表。
x = np.array([2,3,1,0])
nam = ['col1', 'col2', 'col3', 'col4']
I use pd.DataFrame
to convert x
我使用pd.DataFrame
来转换x
y = pd.DataFrame(x, columns=nam)
But I have this error message : 但是我有这个错误消息:
ValueError: Shape of passed values is (1, 4), indices imply (4, 4) ValueError:传递值的形状为(1,4),索引暗示(4,4)
I tried to adjust the index parameter but I can't find the solution. 我试图调整索引参数但我找不到解决方案。
I want my dataframe to look like this: 我希望我的数据框看起来像这样:
col1 col2 col3 col4
2 3 1 0
Another simplier solution with []
: 使用[]
另一个简化解决方案:
x = np.array([2,3,1,0])
nam = ['col1', 'col2', 'col3', 'col4']
print (pd.DataFrame([x], columns=nam))
col1 col2 col3 col4
0 2 3 1 0
you should reshape your input array: 你应该重塑你的输入数组:
In [6]: pd.DataFrame(x.reshape(1,4), columns=nam)
Out[6]:
col1 col2 col3 col4
0 2 3 1 0
or bit more flexible: 或者更灵活一点:
In [11]: pd.DataFrame(x.reshape(len(x) // len(nam), len(nam)), columns=nam)
Out[11]:
col1 col2 col3 col4
0 2 3 1 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.