【问题标题】:How to count non-zeroes values using binned_statistic如何使用 binned_statistic 计算非零值
【发布时间】:2019-02-12 22:14:43
【问题描述】:

我需要有效地处理非常大的一维数组,为每个 bin 提取一些统计信息,我发现 scipy.stats 中的 binned_statistic 函数非常有用,因为它包含一个非常有效的“统计”参数。

我想执行“计数”功能,但不考虑零值。

我在同一个数组上与滑动窗口(pandas 滚动函数)并行工作,它可以很好地将零替换为 NaN,但这种行为并不适用于我的案例。

这是我正在做的一个玩具示例:

import numpy as np
import pandas as pd
from scipy.stats import binned_statistic

# As example with sliding windows, this returns just the length of each window:
a = np.array([1., 0., 0., 1.])
pd.Series(a).rolling(2).count() # Returns [1.,2.,2.,2.]

# You can make the count to do it only if not zero:
nonzero_a = a.copy()
nonzero_a[nonzero_a==0.0]='nan'
pd.Series(nonzero_a).rolling(2).count()   # Returns [1.,1.,0.,1.]

# However, with binned_statistic I am not able to do anything similar:
binned_statistic(range(4), a, bins=2, statistic='count')[0] 
binned_statistic(range(4), nonzero_a, bins=2, statistic='count')[0]
binned_statistic(range(4), np.array([1., False, None, 1.], bins=2, statistic='count')[0]

之前的所有运行都提供相同的输出:[2., 2.] 但我期待 [1., 1.]。

找到的唯一选择是传递一个自定义函数,但它的性能比实际案例中实现的函数差得多。

binned_statistic(range(4), a, bins=2, statistic=np.count_nonzero)

【问题讨论】:

    标签: python pandas numpy scipy bins


    【解决方案1】:

    我找到了一种简单的方法来复制将数组转换为 0-1 并应用 sum 的非零计数:

     # Transform all non-zero to 1s
     a = np.array([1., 0., 0., 2.])
     nonzero_a = a.copy()
     nonzero_a[nonzero_a>0.0]=1.0     # nonzero_a = [1., 0., 0., 1.]
    
     binned_statistic(np.arange(len(nonzero_a)), nonzero_a, bins=bins, statistic='sum')[0]   # Returns [1.0, 1.0]
    

    【讨论】:

      猜你喜欢
      • 2019-11-07
      • 2017-05-26
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2020-11-14
      相关资源
      最近更新 更多