假设我有以下内容:
x1 = [1, 3, 2, 4]
同时:
x2 = [0, 1, 1, 0]
具有相同形状
现在我想要“将x2放在x1之上”,并且对应于x2的数字,将x1中所有数字相加。
因此,最终结果为:
end = [1+4 ,3+2] # end[0] is the sum of all numbers of x1 where a 0 was in x2
这是一个天真的实现,使用列表来进一步澄清问题。
store_0 = 0
store_1 = 0
x1 = [1, 3, 4, 2]
x2 = [0, 1, 1, 0]
for value_x1 ,value_x2 in zip(x1 ,x2):
if value_x2 == 0:
store_0 += value_x1
elif value_x2 == 1:
store_1 += value_x1
所以我的问题是: 有没有一种方法在NumPy中实现这个功能,而不使用循环或者其他更快的方法?
x2==1
返回一组真/假值,可以用于过滤其他操作。因此,x1[x2==0].sum()
和x1[x2==1].sum()
执行了你所需要的两个操作。 - Tim Robertsx2
可能是类似于[0 1 0 2 0 3 ...]
这样的东西? - Brad Day