天天看點

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
           

官方文檔