Python 如何通过逐行添加numpy数组来创建数据帧
所以我得到了一堆流式阵列,我想将它们附加到数据帧中。我试着做如下的事情Python 如何通过逐行添加numpy数组来创建数据帧,python,pandas,Python,Pandas,所以我得到了一堆流式阵列,我想将它们附加到数据帧中。我试着做如下的事情 df = pd.DataFrame(columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y']) outputs = get_outputs() for xp, yp in zip(outputs, labels): ex = np.append(xp, yp) print(ex) print(ex.shape)
df = pd.DataFrame(columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
outputs = get_outputs()
for xp, yp in zip(outputs, labels):
ex = np.append(xp, yp)
print(ex)
print(ex.shape)
#trying here to create row-dataframe
exdf = pd.DataFrame(ex, columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
#want to append the row to the main dataframe
df.append(exdf)
我得到的输出和错误如下
[ 4.49039745 -9.63315201 7.70181465 -15.19582367 12.6580925
-1.17788887 -5.21339655 2.6664052 2.96283174 1.22973883
6. ]
(11,)
...
ValueError: Shape of passed values is (11, 1), indices imply (11, 11)
我该怎么做
编辑:
在回答中加入变化后
exdf = pd.DataFrame([ex], columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
print(exdf)
df.append(exdf)
print(df[:1])
我收到空的数据帧
Out
1 2 3 4 ... 8 9 10 y
0 4.490397 -9.633152 7.701815 -15.195824 ... 2.666405 2.962832 1.229739 6.0
[1 rows x 11 columns]
Empty DataFrame
Columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, y]
Index: []
在for循环中添加
[]
for xp, yp in zip(outputs, labels):
ex = np.append(xp, yp)
print(ex)
print(ex.shape)
#trying here to create row-dataframe
exdf = pd.DataFrame([ex], columns=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'y'])
#want to append the row to the main dataframe
df=df.append(exdf)
我更新了我的帖子。现在由于某种原因,dataframe是empty@YohanRoth请尝试
pd.DataFrame(例如[:,None],columns=['1','2','3','4','5','6','7','8','9','10','y'])
@YohanRoth同样,您需要将其重新分配df=df.append(…)
,pandas中的append与python中列表的append不同,我们需要将其重新分配