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

pandas 赋值代码运算速度优化,麻烦给一点意见,谢谢!

  •  
  •   yellowtail · 2020-11-02 13:32:23 +08:00 · 1038 次点击
    这是一个创建于 1264 天前的主题,其中的信息可能已经有所发展或是发生改变。

    '''

    def fuc_compare(df, i):

    try:
        if (df.loc[i+1].h > df.loc[i].h
             and df.loc[i+1].l > (df.loc[i].l + (df.loc[i].h - df.loc[i].l)/2)):
    
            df.loc['deal',i+1] = 1
    
            return
        if (df.loc[i+1].l < df.loc[i].l
             and df.loc[i+1].h < (df.loc[i].h - (df.loc[i].h - df.loc[i].l)/2)):
            df.loc['deal',i+1] = -1
            return
    except:
        print('^^^^^^^^^error^^^^^^^^^^^^')
        return
    

    i=0 while i < len(df_temp): fuc_compare(df_temp, i) i = i+1

    '''

    第 1 条附言  ·  2020-11-02 18:06:20 +08:00

    '''

    while i < len(df_temp): fuc_compare(df_temp, i) i = i+1 '''

    第 2 条附言  ·  2020-11-02 18:07:01 +08:00
    i=0

    while i < len(df_temp):


    fuc_compare(df_temp, i)


    i = i+1
    第 3 条附言  ·  2020-11-02 18:33:00 +08:00
    最优的办法是 shift 值然后增加一列进行向量化运算
    yellowtail
        1
    yellowtail  
    OP
       2020-11-02 13:39:20 +08:00
    不知道为啥代码格式总不对,还在上班( zf 编外摸鱼发帖),先不改了。。
    yellowtail
        2
    yellowtail  
    OP
       2020-11-02 18:05:18 +08:00
    其实也就是 pandas 中需要跨行取值的问题,如果用 for i,n in df.iterrows():会快一些但是不知道,程序运行时间主要是花在哪一块... 如果 loc 操作相对于 for 循环不算高时间消耗的话
    也许有其他更好的办法..
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1082 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:24 · PVG 07:24 · LAX 16:24 · JFK 19:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.