python - SettingWithCopyWarning,即使在使用 loc (?)

标签 python pandas

<分区>

在我不希望出现的情况下,我会收到 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 会发生?

最佳答案

在情况 1 中,df['A'] 创建了 df 的副本。正如 Pandas documentation 所解释的那样,这可能会在链接时导致意外结果,因此会发出警告。情况 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.

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

df.is_copy = False

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

options.mode.chained_assignment = None

关于python - SettingWithCopyWarning,即使在使用 loc (?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688307/

相关文章:

python - 在脚本中使用 Python 中的 nose 时覆盖现有配置

python - Django 中的当前目录 (os.getcwd) 如何确定?

python - 在 Python 中按阈值计算每列的百分比

python - 在没有 MyClass 的情况下调用 super(MyClass, self).__init__() 的方法?

python - 使用数组的 Numpy 索引

python - 从 pandas.Series 中选择局部最小值和最大值

pandas - 随机数据框列排序

python - 计算每个值在 pandas 列中所占百分比的函数

python - 找不到 Django 404 错误页面

python - 如何将数据框拆分为固定大小的组?