作者:520文雅_293 | 来源:互联网 | 2023-01-28 11:44
我有一个看起来像这样的numpy数组:
a = np.array([35,2,160,56,120,80,1,1,0,0,1])
然后我试图将该数组转换为具有逻辑"一列一值"的pandas数据帧,如下所示:
columns=['age','gender','height',
'weight','ap_hi','ap_lo',
'cholesterol','gluc','smoke',
'alco','active']
values = a
df = pd.DataFrame(a,columns=columns)
这种方法引发了ValueError:传递值的形状是(1,11),索引暗示(11,11).我做错了什么以及如何以正确的方式执行它?
谢谢!
1> jezrael..:
你需要numpy.reshape
:
columns=['age','gender','height',
'weight','ap_hi','ap_lo',
'cholesterol','gluc','smoke',
'alco','active']
a = np.array([35,2,160,56,120,80,1,1,0,0,1])
df = pd.DataFrame(a.reshape(-1, len(a)),columns=columns)
print (df)
age gender height weight ap_hi ap_lo cholesterol gluc smoke alco \
0 35 2 160 56 120 80 1 1 0 0
active
0 1
如果不能清楚地重新读取整形操作,则可以使用更明确的方法向1d数组添加维度 numpy.atleast_2d
pd.DataFrame(np.atleast_2d(a), columns=columns)
或者更简单的添加[]
(但如果真的很多列则更慢):
df = pd.DataFrame([a],columns=columns)
print (df)
age gender height weight ap_hi ap_lo cholesterol gluc smoke alco \
0 35 2 160 56 120 80 1 1 0 0
active
0 1
感谢Divakar的建议:
df = pd.DataFrame(a[None],columns=columns)
print (df)
age gender height weight ap_hi ap_lo cholesterol gluc smoke alco \
0 35 2 160 56 120 80 1 1 0 0
active
0 1
另一个解决方案,谢谢piRSquared:
pd.DataFrame([a], [0], columns)
较短的一个:`pd.DataFrame(a [None],columns = columns)`.