首页 > 解决方案 > 使用警告上下文管理器特别沉默的 Pandas SettingWithCopyWarning?

问题描述

我有显示所有警告的政策:

import warnings
warnings.simplefilter('always')

我想使用上下文管理器消除一些误报 Pandas 警告:

with warnings.catch_warnings():
    warnings.filterwarnings('ignore', category=SettingWithCopyWarning)
    # Some assignment raising false positive warning that should be silenced

# Some assignment actually raising a true positive warning

但是在查看了Pandas source之后,我找不到对象SettingWithCopyWarning在 Pandas 中的定义位置。

有谁知道这个对象在 Pandas 命名空间中定义的位置?

标签: pythonpandaswarnings

解决方案


将评论中的信息合并到一个答案中:

import warnings
import pandas as pd

正如@Andrew 指出的那样,我可以使用专用的 Pandas 上下文管理器来实现它:

with pd.option_context('mode.chained_assignment', None):
    # Chaining Assignment, etc...

或者使用提供的 PSL warnings,我可以找到警告SettingWithCopyWarning对象(感谢 @coldspeed 的 GitHub 链接):

with warnings.catch_warnings():
    warnings.filterwarnings('ignore', category=pd.core.common.SettingWithCopyWarning)
    # Chaining Assignment, etc...

请注意,这两种解决方案的行为似乎相似,但它们并不完全相同:

  • Pandas 上下文管理器暂时更改 Pandas 选项,然后将其恢复;
  • PSL 上下文管理器在不更改 Pandas 选项的情况下捕获特定警告并将其静音。

附加信息

值得将此特定警告转换为错误:

pd.set_option('mode.chained_assignment', 'raise')

这将迫使您的开发避免那些特定的边缘情况,并强制您的代码明确说明它是在视图上工作还是仅在副本上工作。

当然,异常可以像往常一样被捕获:

try:
    # Chaining Assignment, etc...
except pd.core.common.SettingWithCopyError:
    pass

但是在这种情况下,将警告转换为错误可能会迫使您修改模棱两可的代码,直到错误消失,而不是捕获相关的异常。

观察

恕我直言,使用以下命令完全消除这些警告:

pd.set_option('mode.chained_assignment', None)

是一种不好的做法,并且无助于生成更好的代码。


推荐阅读