【问题标题】:Dealing with NaNs in scipy.stats.chisquare在 scipy.stats.chisquare 中处理 NaN
【发布时间】:2019-08-15 06:25:15
【问题描述】:

我正在尝试对一些包含 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?如果没有,最好的处理方式是什么?

【问题讨论】:

    标签: python numpy scipy nan chi-squared


    【解决方案1】:

    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 之前。

    现在如果 x 是 ndarray 它可能会工作:)

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

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 2020-11-19
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多