【问题标题】:ValueError: operands could not be broadcast together with shapes (1521,) (1521,1522) ()ValueError: 操作数不能与形状一起广播 (1521,) (​​1521,1522) ()
【发布时间】:2019-05-24 05:23:46
【问题描述】:

我有一个大数据框df,其中的一个样本是:

           A       B
0          0    4140
1   0.142857    1071
2          0    1196
3   0.090909    2110
4   0.083333    1926
5   0.166667    1388
6          0    3081
7          0    1149
8          0    1600
9   0.058824    1873
10         0    3960
:          :       :
19         0    4315
20         0    2007
21  0.086957    3323
22  0.166667    1084
23       0.5    2703
24         0    1214
25         0    1955
26         0    6750
27         0    3240
28         0    1437
29         0    1701

我将A 列除以B 使用:

df['new_column'] = np.where(df['A'] = 0, 0.0, df['A'].divide(df['B']))*90.0

但是我得到一个错误:

ValueError: operands could not be broadcast together with shapes (1521,) (1521,1522) () 

使用df.A.shape的A列的形状是(1521,) 使用df.B.shape的B列形状为(1521, 1)

我看到形状不同;改变形状会解决问题吗?如果是这样,如何将形状更改为相同?

【问题讨论】:

  • 试试np.where(df['A'] == 0, 0.0, df['A'].div(df['B']))*90.0
  • 感谢@WeNYoBen,但这导致我出现 TypeError: 'int' object is not iterable 错误。你对此有什么想法吗?
  • 你能检查一下 df.dtypes
  • 只是好奇,如果你检查df.A.divide(df.B),为什么还要检查df.A==0

标签: python pandas


【解决方案1】:

错误地将数据帧传递给np.where 时,您的错误看起来非常相似。您能否检查您是否通过了df['A'] 和'df['B'],而不是df[['A']] 和'df[['B']]。因为将混合系列和数据帧传递给 np.where` 会导致这些错误。

示例:(我只使用了你的部分样本数据,所以我的df只有11行)

np.where(df['A'] == 0, 0.0, df[['A']].divide(df['B']))*90.0

返回错误:

ValueError: operands could not be broadcast together with shapes (11,) () (11,12)`

和:

np.where(df['A'] == 0, 0.0, df['A'].divide(df[['B']]))*90.0

返回错误:

TypeError: 'int' object is not iterable

【讨论】:

  • 谢谢 Andy L。有没有办法将数据帧从 df[['A']] 和 'df[['B']] 转换为 df['A'] 和 ' df['B']
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2021-09-12
  • 2017-09-09
  • 2012-10-31
相关资源
最近更新 更多