首页 > 解决方案 > 在 scipy.stats.chisquare 中处理 NaN

问题描述

我正在尝试对一些包含 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? 如果不是,那么处理它们的最佳方法是什么?

标签: pythonnumpyscipynanchi-squared

解决方案


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])

推荐阅读