即使使用loc(?),也可以使用SettingWithCopyWarning [英] SettingWithCopyWarning, even when using loc (?)
问题描述
在我不希望出现的情况下,我得到SettingWithCopyWarning
错误:
I get SettingWithCopyWarning
errors in cases where I would not expect them:
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
和
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
为什么在情况1和2中会发生这种情况?
Why does it happen in case 1 and 2?
推荐答案
在情况1中,df['A']
创建了df
的副本.正如 Pandas文档所述,链接时可能会导致意外结果,从而引发警告.情况2看起来正确,但可能会出现误报:
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:
警告:链接的分配警告/异常旨在 通知用户可能无效的分配.可能有假 肯定;链式作业无意间发生的情况 报告.
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.
要为单个数据框关闭SettingWithCopyWarning
,请使用
To turn off SettingWithCopyWarning
for a single dataframe, use
df.is_copy = False
要完全关闭链接的分配警告,请使用
To turn off chained assignment warnings altogether, use
options.mode.chained_assignment = None
这篇关于即使使用loc(?),也可以使用SettingWithCopyWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!