繁体   English   中英

为什么我不能使用 warnings.filterwarnings 用正则表达式抑制警告

[英]why I cannot suppress warning with regex using warnings.filterwarnings

我想使用正则表达式抑制特定类型的警告。 警告信息是:

C:\Anaconda3\lib\site-packages\pandas\core\indexing.py:420: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy 
self.obj[item] = s

我抑制过滤器的方式:

import warnings
warnings.filterwarnings("ignore", message= ".*A value is trying to.*")

然而,它失败了。 我确实尝试将警告消息的不同部分粘贴到正则表达式中,但仍然失败。 我想知道为什么。

您的正则表达式与正确的消息字符串不匹配。

r".*A Value is trying to.*"不匹配"\\nA value is trying to be.*"因为r"." 匹配除换行符之外的所有内容。

有时,在不查看生成警告的模块的源代码的情况下弄清楚实际的消息字符串是什么可能会很棘手。

尝试仅提供以下代码(不带消息)。可能是您提到的消息与警告不匹配。

导入警告 warnings.filterwarnings("ignore")

这是您遇到的错误吗?

AssertionError: message must be a string

warnings.filterwarnings只为message参数使用一个字符串,而regex不会在那里编译。 如果您确实想抑制此错误,请执行以下操作:

import pandas as pd
warnings.simplefilter("error", pd.core.common.SettingWithCopyWarning)

否则,您可能想要检查避免SettingWithCopyWarning的方法,因为许多其他人也遇到过相同的问题: 如何在Pandas中处理SettingWithCopyWarning?

这不是过滤器警告的工作方式。 在文档中,您可以看到Omitted arguments default to a value that matches everything. 您还可以看到: message (default '') : is a string containing a regular expression that start of the warning message must match

这可以理解为使用动作“一次”会影响每个唯一的文本消息显示一次。 如果消息中的字段可能会更改(例如文件名),则将为每个文件名显示一次警告。

如果您设置 message 参数,那么每个匹配的唯一文本消息将被显示一次。

这是一个小例子:

import warnings
import random

warnings.filterwarnings("ignore", category=UserWarning)
warnings.warn("You won't see this warning")

message_formater = "this message with number {} will be displayed once"

# deactivating previously created filter
warnings.resetwarnings()
# applying new filter
warnings.filterwarnings("once", message_formater.format("(.*)"), category=UserWarning)

for i in range(100):
    warnings.warn(message_formater.format(random.randint(0, 3)))
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:8: UserWarning: this message with number 0 will be displayed once

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:8: UserWarning: this message with number 3 will be displayed once

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:8: UserWarning: this message with number 1 will be displayed once

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:8: UserWarning: this message with number 2 will be displayed once

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM