如何为 python 中的一个函数或封闭的代码行抑制 "UserWarning"

How to suppress "UserWarning" for one single function or enclosed line of code in python

我正在为数据框中的每个变量计算 Anderson Darling k 样本统计数据,其中包含该数据框的子集,并将显着性水平作为文本添加到循环生成的图中。 在我的图表生成之前,测试会为每个正在打印的计算生成一个冗长的“UserWarning”。

有没有办法只针对一行代码抑制“UserWarning”。
例如,R 有一个函数 suppressWarnings() 可以抑制括号内代码的警告。我本可以在 R 中传递 suppressWarnings(stats.anderson_ksamp([a,b]) 以确保没有出现 UserWarning。

from scipy import stats
a = np.random.normal(size=50)
b = np.random.normal(loc=0.5, size=30)
stats.anderson_ksamp([a,b])

输出:

<ipython-input-91-91b6d1abc8ed>:1: UserWarning: p-value floored: true value smaller than 0.001
  stats.anderson_ksamp([np.random.normal(size=50), np.random.normal(loc=0.5, size=30)])
Out[91]: Anderson_ksampResult(statistic=7.638735956038192, critical_values=array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546]), significance_level=0.001)

当我在循环中使用此代码时,它会为每次计算生成多个此类警告。
有没有办法抑制这些 UserWarnings
a) 函数:very_useful_suppressor_function(stats.anderson_ksamp([a,b]))

b) 一种在 1 个 jupyter notebook 单元格中抑制警告的方法

c) 任何其他方式

要用随机数重现问题:_

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

from scipy.stats import anderson_ksamp
from scipy.stats import ks_2samp
a = np.random.normal(size=50)
b = np.random.normal(loc=0.5, size=30)
stats.anderson_ksamp([a,b])


#%%% 
college = pd.DataFrame(np.random.randint(1,1000, size=(10,10)))
college
college[0:5]

#%%% 
## Boxplots
subset_df = college[0:5]
base_df = college
var_main = 0
ovars = np.setdiff1d(subset_df.columns, var_main)
n = len(ovars)
ovars

#%%% 
for var in ovars:
    fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(12,2), facecolor='w')
    
    s1 = base_df[var]
    s2 = subset_df[var]
    adt = anderson_ksamp([s1,s2], midrank=True)
    kst = ks_2samp(s1,s2, 'two-sided')
    plt.figtext(0, 1, 'AD test: sig-lvl ='+str(round(adt[2],5)))
    plt.figtext(0, 0.9, 'KS test: p-val ='+str(kst[1].round(5)))
  
    ax1 = plt.subplot(211)
    sns.boxplot(x=subset_df[var], width=0.4, color='thistle', fliersize=3)
    plt.axis('off')
    ax1.set(title = '-'*20+'\n'+str(var))
    
    ax2 = plt.subplot(212, sharex=ax1)
    box = sns.boxplot(x=base_df[var], width=0.5, color='cadetblue', fliersize=3)
    ax2.set(xlabel=None)
    ax2.tick_params(left=False);

在浪费了这么多 space 之后得到了情节:

C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
  adt = anderson_ksamp([s1,s2], midrank=True)

有一种方法可以使用 with 语句。
source

### a) Define function to suppress warnings

import warnings

## For UserWarning
def fxnUw():
    warnings.warn("UserWarning arose", UserWarning)

## For DeprecationWarning
 def fxnDw():
     warnings.warn("deprecated", DeprecationWarning)
### b) with statement to suppress

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxnUw()
    # code starts here #