V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
admirez
V2EX  ›  Python

有没有 reset 的 cumsum 函数

  •  
  •   admirez · 2020-10-30 12:28:50 +08:00 via iPhone · 1173 次点击
    这是一个创建于 1274 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如[-1,-1,-1,1,1,1,1,-1,-1 ]。

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


    最好是高效率的
    necomancer
        1
    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
        2
    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
        3
    admirez  
    OP
       2020-10-31 09:42:45 +08:00 via iPhone
    @necomancer 非常感谢,我试试看
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1861 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:34 · PVG 00:34 · LAX 09:34 · JFK 12:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.