在大型数据帧上执行add()
和combine_first()
之类的操作时,出现以下运行时错误:
ValueError: operands could not be broadcast together with shapes (680,) (10411,)
广播错误似乎经常使用Numpy(矩阵尺寸不匹配)发生,但是我不明白为什么它会影响我的多索引数据帧/系列。每个连接元素都会产生运行时错误:
我的代码:
# I want to merge two dataframes data1 and data2
# add up the 'requests' column
# merge 'begin' column choosing data1-entries first on collision
# merge 'end' column choosing data2-entries first on collision
pd.concat([\
data1["begin"].combine_first(data2["begin"]),\
data2["end"].combine_first(data1["end"]),\
data1["requests"].add(data2["requests"], fill_value=0)\
], axis=1)
我的资料:
# data1
requests begin end
IP sessionID
*1.*16.*01.5* 20 9 2011-12-16 13:06:23 2011-12-16 16:50:57
21 3 2011-12-17 11:46:26 2011-12-17 11:46:29
22 15 2011-12-19 10:10:14 2011-12-19 16:10:47
23 9 2011-12-20 09:11:23 2011-12-20 13:01:12
24 9 2011-12-21 00:15:22 2011-12-21 02:50:22
...
6*.8*.20*.14* 6283 1 2011-12-25 01:35:25 2011-12-25 01:35:25
20*.11*.3.10* 6284 1 2011-12-25 01:47:45 2011-12-25 01:47:45
[680 rows x 3 columns]
# data2
requests begin end
IP sessionID
*8.24*.135.24* 9215 1 2011-12-29 03:14:10 2011-12-29 03:14:10
*09.2**.22*.4* 9216 1 2011-12-29 03:14:38 2011-12-29 03:14:38
*21.14*.2**.22* 9217 12 2011-12-29 03:16:06 2011-12-29 03:19:45
...
19*.8*.2**.1*1 62728 2 2012-03-31 11:08:47 2012-03-31 11:08:47
6*.16*.10*.155 77282 1 2012-03-31 11:19:33 2012-03-31 11:19:33
17*.3*.18*.6* 77305 1 2012-03-31 11:55:52 2012-03-31 11:55:52
6*.6*.2*.20* 77308 1 2012-03-31 11:59:05 2012-03-31 11:59:05
[10411 rows x 3 columns]
最佳答案
我不知道为什么,也许是错误或某些东西,但是明确指出将每个系列的所有行与[:]
一起使用可以按预期工作。没有错误。
print pd.concat([\
data1["begin"][:].combine_first(data2["begin"][:]),\
data2["end"][:].combine_first(data1["end"][:]),\
data1["requests"][:].add(data2["requests"][:], fill_value=0)\
], axis=1)
关于python - Pandas :ValueError-操作数不能与形状一起广播,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29082927/