gpt4 book ai didi

python - Pandas:ValueError - 操作数无法与形状一起广播

转载 作者:行者123 更新时间:2023-12-01 04:47:42 24 4
gpt4 key购买 nike

在大型数据帧上执行 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com