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
mulandidi
V2EX  ›  Python

Python 小白, 请教各位大佬一个如何能够优化这个方法?

  •  
  •   mulandidi · 2020-05-10 21:23:21 +08:00 · 2113 次点击
    这是一个创建于 1453 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我有一个很长的 dataframe,100w 左右吧, df = pd.DataFrame(columns =['id']),我现在想要重新计算一个新列, 逻辑是 在第 i 行,利用第 i,i-1,i-2 的 id 列三个数值计算,我现在是用循环计算的,感觉很慢,非常丧,用多线程啥的感觉好像太重了

    不知道大家有什么好的方法,感谢

    7 条回复    2020-05-11 11:38:33 +08:00
    llsquaer
        1
    llsquaer  
       2020-05-10 21:39:16 +08:00
    没明白你具体..如果计算其中三行 某列的数据,直接取 index 就行了啊..100w 数据也是毫秒的事情..还用什么循环?
    imn1
        2
    imn1  
       2020-05-10 22:00:51 +08:00   ❤️ 1
    你搜搜官方文档关于移动统计的章节,应该是“Expanding Windows”相关的内容
    移动统计就是用前 n 行数据计算当前新数据,时序类型数据经常需要,例如证券
    liprais
        3
    liprais  
       2020-05-10 22:02:40 +08:00 via iPhone
    sql window function lag
    yzc27
        4
    yzc27  
       2020-05-10 22:06:03 +08:00 via iPhone
    用 apply()?
    renmu
        5
    renmu  
       2020-05-10 22:16:38 +08:00 via Android
    d[i]=d[i-1]+d[i-2]这样?,直接操作
    mulandidi
        6
    mulandidi  
    OP
       2020-05-10 22:40:55 +08:00
    @imn1 对,是时序数据,感谢了,用自带的 rolling 可以
    Latin
        7
    Latin  
       2020-05-11 11:38:33 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2245 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:05 · PVG 14:05 · LAX 23:05 · JFK 02:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.