pandas SettingWithCopyWarning,即使使用 loc (?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23688307/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:03:30  来源:igfitidea点击:

SettingWithCopyWarning, even when using loc (?)

pythonpandas

提问by Amelio Vazquez-Reina

I get SettingWithCopyWarningerrors in cases where I would not expect them:

SettingWithCopyWarning在我不期望它们的情况下,我会收到错误:

N.In <38>: # Column B does not exist yet
N.In <39>: df['B'] = df['A']/25
N.In <40>: df['B'] = df['A']/50

/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/pandas/core/indexing.py:389: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  self.obj[item] = s

and

N.In <41>: df.loc[:,'B'] = df['A']/50

/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/pandas/core/indexing.py:389: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  self.obj[item] = s

Why does it happen in case 1 and 2?

为什么会在情况 1 和 2 中发生?

回答by kxsong

In case 1, df['A']creates a copy of df. As explained by the Pandas documentation, this can lead to unexpected results when chaining, thus a warning is raised. Case 2 looks correct, but false positives are possible:

在情况 1 中,df['A']创建df. 正如Pandas 文档所解释的那样,这可能会在链接时导致意外结果,因此会引发警告。情况 2 看起来是正确的,但也可能出现误报:

Warning: The chained assignment warnings / exceptions are aiming to inform the user of a possibly invalid assignment. There may be false positives; situations where a chained assignment is inadvertantly reported.

警告:链式分配警告/异常旨在通知用户可能无效的分配。可能存在误报;无意中报告了链式分配的情况。

To turn off SettingWithCopyWarningfor a single dataframe, use

要关闭SettingWithCopyWarning单个数据帧,请使用

df.is_copy = False

To turn off chained assignment warnings altogether, use

要完全关闭链式分配警告,请使用

options.mode.chained_assignment = None

回答by Charlie Haley

Another solution that should suppress the warning:

另一个应该抑制警告的解决方案:

df = df.copy()
df['B'] = df['A']/25
df['B'] = df['A']/50