在 scipy.stats.chisquare 中处理 NaN

Dealing with NaNs in scipy.stats.chisquare

我正在尝试对一些包含 NaN 的数据执行 chi^2 检验。这是一个 MWE:

from scipy.stats import chisquare as chi2
import numpy as np
x = [16, 18, 16, 14, 12, 12]
chi2(x)

产出

Power_divergenceResult(statistic=2.0, pvalue=0.8491450360846096)

但是

x[-1] = np.nan
chi2(x)

给予

Power_divergenceResult(statistic=nan, pvalue=nan)

使用

敷面膜
mask = ~np.isnan(x)
chi2(x[mask])

结果

TypeError                                 Traceback (most recent call last)
<ipython-input-13-3c009fd66f63> in <module>
----> 1 chi2(x[mask])

TypeError: only integer scalar arrays can be converted to a scalar index

我认为(希望)我的实际数据中的 NaN 是导致问题的原因。 scipy.stats.chisquare 是否有处理 NaN 的内置方法,例如,spearmanr 是否有处理其 nan_policy 的方法?如果不是,最好的处理方法是什么?

x 是一个列表;布尔数组(就此而言,任何数组)不能用于索引列表。

In [244]: x = [16, 18, 16, 14, 12, 12]                                          
In [245]: x[-1] = np.nan                                                        
In [246]: mask = ~np.isnan(x)                                                   
In [247]: x[mask]                                                               
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-247-fee3ce9a3be1> in <module>
----> 1 x[mask]

TypeError: only integer scalar arrays can be converted to a scalar index
In [248]: mask                                                                  
Out[248]: array([ True,  True,  True,  True,  True, False])

调用 chi2 之前发生该错误。

现在如果 xndarray 它可能会起作用 :)

In [249]: x = np.array([16, 18, 16, 14, 12, 12])                                
In [250]: x[mask]                                                               
Out[250]: array([16, 18, 16, 14, 12])