Pandas SettingWithCopyWarning 解决方法求教

2018-12-14 11:27:07 +08:00
 youthfire

想要修改其中一个序列

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 的正确写法应该是什么呢?

1685 次点击
所在节点    Python
4 条回复
imn1
2018-12-14 11:57:44 +08:00
用 str.slice()试试
congeec
2018-12-14 12:12:17 +08:00
df['description'] = df['description'].map(str.upper).map(lambda x: x[:30])
lance6716
2018-12-14 12:35:20 +08:00
df = df.copy() 然后再
youthfire
2018-12-14 12:47:25 +08:00
@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)

也谢谢所有回答者。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/517479

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX