【问题标题】:Efficient way to compute number of nonzeros with a rolling window in pandas?在熊猫中使用滚动窗口计算非零数的有效方法?
【发布时间】:2021-03-04 18:46:47
【问题描述】:

我有一个大数据框,简化为:

>>> df = pd.DataFrame(np.random.randint(0,2,size=(100, 4)), columns=list('ABCD'))

    A  B  C  D
0   1  0  1  0
1   0  0  0  0
2   1  0  0  0
3   0  1  1  1
4   0  1  1  1
.. .. .. .. ..
95  1  0  0  1
96  0  1  1  0
97  0  0  1  1
98  1  1  1  0
99  0  0  0  0

我想获得一个新的数据框,稍后我将使用它作为掩码来过滤掉一些值。此掩码应显示大小为 10 的滚动窗口中非零元素的数量。

我正在使用的解决方案是:

df.rolling(10).apply(lambda x: x.astype(bool).sum(axis=0))

它可以完成这项工作,但我的原始数据框非常大,所以如果可能的话,我会尝试优化这个过程,因为对于数百万个值,它需要相当多的时间。我想在创建滚动窗口之前移动 astype(bool) 部分,但似乎我仍然需要拥有 apply(lambda ...) 构造,这是这里真正的效率瓶颈。

【问题讨论】:

标签: python pandas


【解决方案1】:

不使用apply 会有所帮助:

(df != 0).rolling(10).sum()

时间(1000 条记录):

%%time
_ = df.rolling(10).apply(lambda x: x.astype(bool).sum(axis=0))

CPU times: user 517 ms, sys: 13.6 ms, total: 531 ms
Wall time: 522 ms
%%time
_ = (df != 0).rolling(10).sum()

CPU times: user 2.04 ms, sys: 315 µs, total: 2.35 ms
Wall time: 1.45 ms

【讨论】:

    猜你喜欢
    • 2018-07-10
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多