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

关于 pandas 的 apply 性能的一些疑惑

  •  
  •   zh584728 · 2022-09-28 16:10:41 +08:00 · 2070 次点击
    这是一个创建于 568 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有一个 dataframe, 其中的几列需要单独处理

    方案 1 是:

    
        df['foo1'] = df['foo1'].apply(lambda x: func1(x))
        df['foo2'] = df['foo2'].apply(lambda x: func2(x))
        df['foo3'] = df['foo3'].apply(lambda x: func3(x))
        ...
    

    方案 2 是:

        def pipeline(ser):
            ser = (ser.pipe(func1)
                .pipe(func2)
                .pipe(func3))
        
        df = df.apply(lambda x: pipeline(x), axis=1)
    

    在我感觉上是方案 2应该是比方案 1要快的,但是实际运行下来发现方案 2时间更长...

    难道是我理解错了吗,按列处理会更快,即使是使用了 apply

    4 条回复    2022-09-28 17:01:58 +08:00
    cyberpoint
        1
    cyberpoint  
       2022-09-28 16:24:55 +08:00
    不理解
    Renormalization
        2
    Renormalization  
       2022-09-28 16:47:16 +08:00   ❤️ 2
    pandas 按列处理肯定是最快的。<<Python for Finance>>书上的原话是"Working with the columns (Series objects) directly is the fastest approach"。另一句是"The slowest option is to use the apply() method row-by-row; this is like looping on the Python level over all rows".
    ipwx
        3
    ipwx  
       2022-09-28 16:49:12 +08:00   ❤️ 2
    Pandas 是按列存储的。
    zh584728
        4
    zh584728  
    OP
       2022-09-28 17:01:58 +08:00   ❤️ 1
    @Renormalization 是的 我已经试验出来了,一开始以为 apply 的少的会快一些
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3230 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 14:09 · PVG 22:09 · LAX 07:09 · JFK 10:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.