【发布时间】: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