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

Pandas SettingWithCopyWarning 解决方法求教

  •  
  •   youthfire · 2018-12-14 11:27:07 +08:00 · 1679 次点击
    这是一个创建于 1952 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想要修改其中一个序列

    df['description'] = df['description'].str.upper().str[:30]

    运行结果没问题,但总是提示

    A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

    求教这个用.loc 的正确写法应该是什么呢?

    4 条回复    2018-12-14 12:47:25 +08:00
    imn1
        1
    imn1  
       2018-12-14 11:57:44 +08:00
    用 str.slice()试试
    congeec
        2
    congeec  
       2018-12-14 12:12:17 +08:00
    df['description'] = df['description'].map(str.upper).map(lambda x: x[:30])
    lance6716
        3
    lance6716  
       2018-12-14 12:35:20 +08:00 via Android   ❤️ 1
    df = df.copy() 然后再
    youthfire
        4
    youthfire  
    OP
       2018-12-14 12:47:25 +08:00 via iPhone
    @lance6716 感谢,特地去了解了下 df.copy().

    我的例子确实写的不太好,其实是我用另一个 cf 名 copy 了原来的 df,写的是 cf['description'] = cf['description'].str.upper().str[:30],没了解 cf=df 不等于 df.copy,Stackflow 的解释更多些:

    Because if you don't make a copy then the indices can still be manipulated elsewhere even if you assign the dataFrame to a different name.

    For example:

    df2 = df
    func1(df2)
    func2(df)
    func1 can modify df by modifying df2, so to avoid that:

    df2 = df.copy()
    func1(df2)
    func2(df)

    也谢谢所有回答者。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5411 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 05:46 · PVG 13:46 · LAX 22:46 · JFK 01:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.