Pandas SettingWithCopyWarning:试图在 DataFrame 切片的副本上设置值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33727667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
提问by Dance Party
I keep getting the warning in the subject in the following situations:
在以下情况下,我不断收到该主题的警告:
df.rename(columns={'one':'one_a'}, inplace=True)
df.drop(['one', 'two', 'three'], axis=1, inplace=True)
df.rename(columns={'one':'one_a'}, inplace=True)
df.drop(['one', 'two', 'three'], axis=1, inplace=True)
How do I fix?
我该如何解决?
回答by maxymoo
Easiest fix (and probably good programming practice) would be to not do inplace operations, e.g.
最简单的修复(也可能是良好的编程实践)是不进行就地操作,例如
df2 = df.rename(columns={'one':'one_a'})
回答by tupan
I had a similar problem and to fix I did the following:
我有一个类似的问题,为了解决我做了以下事情:
new_df = df.copy()
new_df.rename(columns={'one':'one_a'}, inplace=True)
new_df.drop(['one', 'two', 'three'], axis=1, inplace=True)
Or you can do
或者你可以做
df.is_copy = False
You were probably using a copy of your original DF (ex: you were manipulating your DF before that) and that's why you were receiving the warning. More on copy:
您可能正在使用原始 DF 的副本(例如:您在此之前操作了 DF),这就是您收到警告的原因。更多关于副本: