有没有 reset 的 cumsum 函数

2020-10-30 12:28:50 +08:00
 admirez
比如[-1,-1,-1,1,1,1,1,-1,-1 ]。

能变成 -1,-2,-3,1,2,3,4,-1,-2


最好是高效率的
1185 次点击
所在节点    Python
3 条回复
necomancer
2020-10-30 16:40:46 +08:00
a = np.array([-1,-1,-1,1,1,1,1,-1,-1])
bounds = np.r_[0, np.argwhere(np.diff(a>0, prepend=0)).ravel(), a.shape[0]]
np.concatenate([np.cumsum(a[i:j]) for i, j in zip(bounds[:-1], bounds[1:])])
necomancer
2020-10-30 16:53:32 +08:00
可能快一点,尤其是 1, -1 交错很厉害的时候
import pandas as pd
b = pd.Series(np.insert(a, np.argwhere(np.diff(a>0, prepend=0)).ravel(), 0))
cum = b.cumsum()
cum = (cum -cum.where(b==0).ffill().fillna(0)).values
cum = cum[cum!=0]
admirez
2020-10-31 09:42:45 +08:00
@necomancer 非常感谢,我试试看

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/720123

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX