如何有效消除Python pandas中的SettingWithCopyWarning警告?
- 内容介绍
- 文章标签
- 相关推荐
本文共计267个文字,预计阅读时间需要2分钟。
1. 错误信息提示:在`Anaconda/lib/site-packages/pandas/core/indexing.py`的第1676行,存在`SettingWithCopyWarning`警告。原因是在尝试对一个从DataFrame中切片的副本设置值。建议使用`.loc[row_indexer, col_indexer]=value`代替。详情请参考`t`中的注意事项。
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 insteadSee the caveats in the documentation: pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copyself._setitem_single_column(ilocs[0], value, pi)
2.解决方案
将选项 mode.chained_assignment设置为以下值之一:
- '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官方文档
pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
本文共计267个文字,预计阅读时间需要2分钟。
1. 错误信息提示:在`Anaconda/lib/site-packages/pandas/core/indexing.py`的第1676行,存在`SettingWithCopyWarning`警告。原因是在尝试对一个从DataFrame中切片的副本设置值。建议使用`.loc[row_indexer, col_indexer]=value`代替。详情请参考`t`中的注意事项。
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 insteadSee the caveats in the documentation: pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copyself._setitem_single_column(ilocs[0], value, pi)
2.解决方案
将选项 mode.chained_assignment设置为以下值之一:
- '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官方文档
pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

