我是一个Python初学者。我收到一条错误消息“ValueError:操作数无法与形状一起广播”。
这是我的数据:
import numpy as np
spent = np.array([
10, 10, 13, 12, 109, 17, 31, 1, 39, 41, 45,
41, 71, 161, 39, 115, 5, 51, 58, 334, 165, 1032,
40, 52, 21, 68, 79, 482, 10, 265, 60, 67, 12,
53, 188, 32, 397, 51, 17, 156, 100, 85, 53, 95,
68, 308, 53, 675, 78, 27, 219, 45, 45, 30, 61,
16, 72, 80, 96, 1386, 370, 16, 81, 28, 43, 90,
33, 66, 77])
visit = np.array([
19, 13, 16, 16, 18, 9, 12, 3, 15, 16, 16, 3, 4, 11, 11, 11, 11,
12, 12, 12, 13, 13, 14, 14, 15, 15, 5, 6, 6, 7, 7, 7, 7, 7,
17, 17, 8, 8, 8, 4, 4, 13, 8, 4, 4, 9, 20, 10, 11, 11, 14,
12, 12, 15, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 16, 16, 18, 11,
6])
我的工作是选择花费>100并一起访问>10。因此,我想在访问次数超过 10 次的人中找到支付超过 100 美元的人。 我已经尝试过以下代码。
a=spent[spent>100] & [visit>10]
print(a)
但是,我收到一条错误消息“ValueError:操作数无法与形状一起广播”。你能告诉我如何处理这个问题吗?我只是不知道。
最佳答案
IIUC,您不需要像您所做的那样spent
本身使用面具:
In[16]:
a=(spent>100) & (visit>10)
a
Out[16]:
array([False, False, False, False, True, False, False, False, False,
False, False, False, False, True, False, True, False, False,
False, True, True, True, False, False, False, False, False,
False, False, False, False, False, False, False, True, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, True, False, False, False,
False, False, False, False, False, True, True, False, False,
False, False, False, False, False, False], dtype=bool)
这为您提供了一个 bool 掩码,仅当两个数组中都满足两个条件时,该掩码才为True
,然后您可以使用它来掩码原始数组
因此使用它来对抗spent
:
In[18]:
spent[a]
Out[18]: array([ 109, 161, 115, 334, 165, 1032, 188, 219, 1386, 370])
您的错误是您屏蔽了原始数组,该数组生成的数组与您尝试针对 visit
广播的数组的形状不同:
print(spent[spent>100].shape)
print((visit>10).shape)
(16,)
(69,)
您可以将条件复合到同一个掩码中:
In[20]:
spent[(spent > 100) & (visit > 10)]
Out[20]: array([ 109, 161, 115, 334, 165, 1032, 188, 219, 1386, 370])
产生相同的结果
关于python - Numpy错误: operands could not be broadcast together with shapes 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47265369/