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

函数中修改外部 dataframe 遇到的问题

  •  
  •   yellowtail · 2020-06-11 18:30:50 +08:00 · 1944 次点击
    这是一个创建于 1408 天前的主题,其中的信息可能已经有所发展或是发生改变。
    a = pd.DataFrame()
    def fuc(a):
    a = a.append({'1':1})
    return
    fuc(a)

    结果 a 还是空的 df

    求提示
    5 条回复    2020-06-12 18:03:59 +08:00
    xiaolinjia
        1
    xiaolinjia  
       2020-06-11 19:57:23 +08:00
    答案是此 a 非彼 a 。你分清全局变量和局部变量再说吧。
    答案是用 global
    nuistzhou
        2
    nuistzhou  
       2020-06-11 21:02:38 +08:00   ❤️ 1
    楼上说的 global 是可以解决楼主的问题。
    不过一般不太建议直接在函数里修改全局变量,返回修改后的变量比较好一些。
    renmu123
        3
    renmu123  
       2020-06-12 00:07:52 +08:00 via Android   ❤️ 1
    用 global 是个坏习惯,可以在函数中返回 a,再把函数值赋值给 a
    fasionchan
        4
    fasionchan  
       2020-06-12 08:59:38 +08:00   ❤️ 1
    把 a = pd.DataFrame() 定义在 global 本身就是一个不好的编程习惯,一般将它封装在类或者闭包中,除非你只是临时写一写
    yellowtail
        5
    yellowtail  
    OP
       2020-06-12 18:03:59 +08:00
    感谢回答,最后类和闭包都不熟悉,还是用 global 解决了。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2853 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:33 · PVG 22:33 · LAX 07:33 · JFK 10:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.