python - Numpy:条件总和

标签 python arrays numpy sum

我有以下 numpy 数组:

import numpy as np
arr = np.array([[1,2,3,4,2000],
                [5,6,7,8,2000],
                [9,0,1,2,2001],
                [3,4,5,6,2001],
                [7,8,9,0,2002],
                [1,2,3,4,2002],
                [5,6,7,8,2003],
                [9,0,1,2,2003]
              ])

我理解np.sum(arr, axis=0)来提供结果:

array([   40,    28,    36,    34, 16012])

我想做的(没有 for 循环)是根据最后一列的值对列求和,以便提供的结果是:

array([[   6,    8,   10,   12, 4000],
       [  12,    4,    6,    8, 4002],
       [   8,   10,   12,    4, 4004],
       [  14,    6,    8,   10, 4006]])

我意识到没有循环可能会有些困难,但希望最好...

如果必须使用 for 循环,那将如何工作?

我尝试了 np.sum(arr[:, 4]==2000, axis=0)(我将用 for 循环中的变量替换 2000 ),但是它给出了 2

的结果

最佳答案

您可以使用 np.diff 的巧妙应用在纯 numpy 中执行此操作和 np.add.reduceat . np.diff 将为您提供最右侧列发生变化的索引:

d = np.diff(arr[:, -1])

np.where会将您的 bool 索引 d 转换为 np.add.reduceat 期望的整数索引:

d = np.where(d)[0]

reduceat 也希望看到零索引,并且所有内容都需要移动 1:

indices = np.r_[0, e + 1]

使用 np.r_这里比np.concatenate方便一点因为它允许标量。然后总和变为:

result = np.add.reduceat(arr, indices, axis=0)

这当然可以组合成一行:

>>> result = np.add.reduceat(arr, np.r_[0, np.where(np.diff(arr[:, -1]))[0] + 1], axis=0)
>>> result
array([[   6,    8,   10,   12, 4000],
       [  12,    4,    6,    8, 4002],
       [   8,   10,   12,    4, 4004],
       [  14,    6,    8,   10, 4006]])

关于python - Numpy:条件总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50121980/

相关文章:

python - 在 win32 中读取符号链接(symbolic link)/连接点的目标(通过 Python)

python - 将 Mixer 与 Flask-SQLAlchemy 结合使用

java:当构造函数直接存储用户提供的数组时,除了安全性之外的影响

Java arrays.binary 搜索多个匹配项?

python - 如何根据python中的另一个变量计算非零出现次数?

python - 计算每列或每行非零元素的平均值的有效方法

python - Django:无法更改默认语言

python - 在 Pandas 中合并缺少列的 CSV 文件

ios - 如何在排序数组中将一行代码从 Objective-C 转换为 Swift?

python:numpy:命名数组的串联