Python 是否使用警告上下文管理器设置CopyWarning?

Python 是否使用警告上下文管理器设置CopyWarning?,python,pandas,warnings,Python,Pandas,Warnings,我有显示所有警告的政策: import warnings warnings.simplefilter('always') 我想使用上下文管理器消除一些误报警告: with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=SettingWithCopyWarning) # Some assignment raising false positive warning that should

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

import warnings
warnings.simplefilter('always')
我想使用上下文管理器消除一些误报警告:

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中定义了对象
SettingWithCopyWarning


有人知道此对象在名称空间中的何处定义吗?

以下内容应满足您的要求:

pd.set\u选项('mode.chained\u assignment',无)

取自


然而,请花些时间阅读上面的文章,因为它解释了很多关于该警告的内容。也许你不想总是沉默吧

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

import warnings
import pandas as pd
正如@Andrew指出的,我可以使用专用的上下文管理器来实现它:

with pd.option_context('mode.chained_assignment', None):
    # Chaining Assignment, etc...
或者使用PSL
warnings
,前提是我可以通过CopyWarnings对象找到warnings
设置(感谢GitHub链接的@coldspeed):

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

  • 熊猫上下文管理器临时更改熊猫选项,然后恢复它
  • 捕捉特定警告并使其静音,而不改变选项
其他信息

可以将此特定警告转换为错误:

pd.set_option('mode.chained_assignment', 'raise')
这将迫使您的开发避免那些特定的边缘情况,并迫使您的代码显式地声明它是在视图上工作还是仅在副本上工作

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

try:
    # Chaining Assignment, etc...
except pd.core.common.SettingWithCopyError:
    pass
但在这种情况下,将警告转换为错误可能会迫使您修改不明确的代码,直到错误消失,而不是捕获相关的异常

观察

IMHO,使用以下方法将这些警告完全静音:

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

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

@coldspeed感谢您指出,我错过了它。我正在查找
错误。py
。不,我想特别地使它静音,这就是我使用上下文管理器的原因。我已经知道了。感谢您的回答。
带有pd.option\u context('mode.chained\u assignment',None):
来自链接文章感谢您的链接并指出上下文管理器。我已经把你和@coldspeed的评论合并成了一个答案。我认为这是最适合OP的方式。
pd.set_option('mode.chained_assignment', None)