根据布尔数组获取numpy数组的总和 [英] Take sum of numpy array based on a boolean array

查看:184
本文介绍了根据布尔数组获取numpy数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个numpy数组prodsindex

I have two numpy arrays prods andindex

prods = np.asarray([ 0.5 ,  0.25,  1.98,  2.4 ,  2.1 ,  0.6 ])
index = np.asarray([False,  True,  True, False, False,  True], dtype=bool)

我需要使用index数组计算prods数组中值的总和.我想要的输出是

I need to calculate the sum of the values in prods array using the index array. The output I want to is

res = [0.75, 1.98, 5.1]

index数组中的第一个True之前是False,因此我从prods(.5,.25)中获取前两个元素,并将它们加起来(0.75).索引中的第二个True没有前面的False(因为它前面带有True,所以零位置的False不计数),因此在这种情况下,我仅输出1.98.第三个True前面有两个False,因此我从prods数组(2.4,2.1,0.6)中获取了这些值并将它们求和.有关如何执行此操作的任何想法?

The first True in index array is preceded by a False, so I take the first two elements from prods(.5,.25) and sum them up(0.75). The second True in index has no preceding False (since its preceded by a True, the False at position zero doesn't count), so I simply output 1.98 in this case. The third True is preceded by two False, so I take those values from prods array (2.4,2.1,0.6) and sum them up. Any ideas on how to do this?

我基本上需要类似np.cumsum的东西,但是每次索引中出现True时,我都需要返回累积总和,并将累积总和值重置为零.

I basically need something like np.cumsum but I need to return the cumulative sum every time a True occurs in index and reset the cumulative sum value to zero.

推荐答案

您可以使用 np.split 并使用index数组的> np.where 作为要拆分的位置:

You could use np.split and using np.where of your index array as positions to split:

>>> [arr.sum() for arr in np.split(prods, np.where(index)[0]+1)[:-1]]
[0.75, 1.98, 5.0999999999999996]

由于浮点精度,最后一个不完全是5.1.如果您不想使用FractionDecimal s,那么您将无能为力.

The last one isn't exactly 5.1 because of floating point precision. If you don't want to use Fractions or Decimals there's nothing you can do about that.

您还可以使用 np.add.reduceat 在这里:

You could also use np.add.reduceat here:

>>> np.add.reduceat(prods, np.append([0], (np.where(index)[0]+1)[:-1]))
array([ 0.75,  1.98,  5.1 ])

这篇关于根据布尔数组获取numpy数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆