问题描述
我正在使用该数据帧的子集计算数据帧中每个变量的 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 笔记本单元中警告的方法
或
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,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);
在浪费了这么多空间之后得到了情节:
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
adt = anderson_ksamp([s1,midrank=True)
C:\Users\Rahul\.spyder-py3\temp.py:39: UserWarning: p-value capped: true value larger than 0.25
adt = anderson_ksamp([s1,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 #