gpt4 book ai didi

python : Array group by Sum value

转载 作者:行者123 更新时间:2023-11-30 22:26:39 25 4
gpt4 key购买 nike

存在许多主题来根据另一个数组索引对数组求和,但我找不到我要查找的内容。

我有一个数组[1,1,1,1,2,3,3,0,0,2,4],我想获取迄今为止总和的索引大于或等于4。所以我会得到:

[3,5,9,10]因为:

Sum([1,1,1,1]) >= 4

Sum([2,3]) >= 4

Sum([3,0,0,2]) >= 4

我需要满足总和值的元素的索引。

我可以用循环来完成它,但我正在寻找使用 numpy 等有效地完成它。

最佳答案

您可以将np.wherenp.cumsum结合使用:

import numpy as np

li = [1,1,1,1,2,2,3,0,0,1,4]

print(np.where(np.cumsum(li) % 4 == 0))
# (array([ 3, 5, 9, 10], dtype=int32),)

这里的问题当然是它还会找到总和为 8、12、16、20 等的索引。

不幸的是,我不确定是否有办法“重置”cumsum,如果有的话,你可以这样做 np.where(np.cumsum(li) - 4 == 0)(但目前只会返回 3)。

但是,您可以在每次 cumsum 达到 4 时对数组进行切片,但您不想使用循环。

关于 python : Array group by Sum value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177639/

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