gpt4 book ai didi

python - Numpy:条件总和

转载 作者:太空狗 更新时间:2023-10-30 00:47:27 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com