python - 使用警告上下文管理器特别沉默的 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 命名空间中定义的位置?
解决方案
将评论中的信息合并到一个答案中:
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)
是一种不好的做法,并且无助于生成更好的代码。
推荐阅读
- vuejs2 - Vuex:添加到原型,以便我可以执行 object.save() 之类的操作?
- sql - 使用 unnest 函数在 Presto w/o 中提取数组元素
- python - Maximo 自动化脚本是否可以根据从另一个值列表中的选择启用或禁用来自值列表的值?
- android - 使用 BottomNavigationView 按下后退按钮时未加载上一个片段
- python - 当包含索引的张量的长度大于 32 时,使用 tensorflow.gather_nd 的问题
- javascript - redux reducer 的奇怪行为?
- flutter - Flutter-为什么我看不到下拉列表中的数据
- elasticsearch - 使用 Flink Rich InputFormat 创建 Elasticsearch 的输入格式
- angular - 预期未定义的定义 Karma Jasmine 单元测试用例
- insomnia - 无法发布到 mongo db,“错误:ValidationError: name: Path `name` is required。”