如果我不指望它,我会收到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
和
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中?
答案 0 :(得分:10)
在案例1中,df['A']
会创建df
的副本。正如Pandas documentation所解释的那样,这可能会在链接时导致意外结果,从而引发警告。案例2看起来正确,但可能出现误报:
警告:链式分配警告/异常的目标是 告知用户可能无效的分配。可能有假 阳性;无意中链式分配的情况 报道。
要为单个数据帧关闭SettingWithCopyWarning
,请使用
df.is_copy = False
要完全关闭链式分配警告,请使用
options.mode.chained_assignment = None
答案 1 :(得分:3)
应该取消警告的另一种解决方案:
df = df.copy()
df['B'] = df['A']/25
df['B'] = df['A']/50