【问题标题】:What is the best approach to this issue related to cumulative sum per section?与每个部分的累积总和有关的这个问题的最佳方法是什么?
【发布时间】:2021-12-24 03:56:39
【问题描述】:

我有这些信息:
[0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1]

并且只需要在零之间的部分连续添加15,结果:
[0,15,30,45,60,75,0,15,30,45,0,15,30,45,60,0,15,30,45]

【问题讨论】:

标签: python pandas numpy sum


【解决方案1】:
import numpy
l = np.array([0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1])
l *= 15
s = np.hstack([np.cumsum(v) for v in np.split(l, np.where(l==0)[0])])
print(s)

np.split 需要一个要拆分的数组和一个可迭代的剪切。 np.where 为您提供所有索引i 其中l[i] == 0np.cumsum 对所有这些进行累积总和,然后 np.hstack 将它们重新组合在一起。

【讨论】:

  • 我想知道为什么是-1。我不是想打高尔夫球,这就是我的做法。
【解决方案2】:

伪代码

create an empty list which will be the result
initialize a counter at 0
for each element of the original list
    add 1 to the counter if the element is not 0 else reset the counter to 0
    append to the result list 15 times the counter

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多