在大 pandas 中如何在移动的窗口上计算“Countif”? [英] In pandas how to calculate 'Countif' on a moving window basis?

查看:101
本文介绍了在大 pandas 中如何在移动的窗口上计算“Countif”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

A = pd.DataFrame([[1, 5, -2], [2, 4, -4], [3, 3, -1], [4, 2, 2], [5, 1, 4]],
             columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])

说你想计算数字观察<在C列中的0在最后3次观察中基于滚动。在excel中,您可以在具有条件的指定窗口中滑动countif计算,并且所需的结果将是:

Say you want to calculate the number observations < 0 in the column C over the last 3 observations on a rolling basis. In excel you would slide a 'countif' calculation over a specified window with the condition and the desired result would be:

D = # of x < 0 on a rolling window basis of size 3

A
Out[79]: 
   A  B  C  D
1  1  5 -2  
2  2  4 -4
3  3  3 -1  3
4  4  2  2  2
5  5  1  4  1

如何使用Pandas以高效(Pythonic)方式执行此操作?

How can I do this in an efficient(Pythonic) way using Pandas?

感谢

推荐答案

您可以使用 rolling_sum 在一列布尔:

You can use rolling_sum on a column of bools:

>>> A["D"] = pd.rolling_sum((A["C"] < 0), 3)
>>> A
   A  B  C   D
1  1  5 -2 NaN
2  2  4 -4 NaN
3  3  3 -1   3
4  4  2  2   2
5  5  1  4   1

这是因为True〜1和False〜0,我们有

This works because True ~ 1 and False ~ 0, and we have

>>> A["C"] < 0
1     True
2     True
3     True
4    False
5    False
Name: C, dtype: bool

这篇关于在大 pandas 中如何在移动的窗口上计算“Countif”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆