天天看点

python pandas SettingWithCopyWarning 解决方案

1.错误信息

D:\Anaconda\lib\site-packages\pandas\core\indexing.py:1676: SettingWithCopyWarning:

A value is trying to be set on a copy of a slice from a DataFrame.

Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

self._setitem_single_column(ilocs[0], value, pi)

2.解决方案

  • 'warn',默认值,表示SettingWithCopyWarning打印 a。
  • 'raise'意味着熊猫会提出一个SettingWithCopyException 你必须处理的问题。
  • None将完全抑制警告。
>>> pd.set_option('mode.chained_assignment','warn')
>>>dfb[dfb['a'].str.startswith('o')]['c'] = 42

Traceback (most recent call last)
     ...
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
           

官方文档