繁体   English   中英

Pandas:如何计算一个列(按日期分组)上的滚动 window 并计算另一列的不同值?

[英]Pandas: how to calculate a rolling window over one column (grouped by date) and count distinct values of another column?

我试图在 Pandas 中计算一个日期列上的滚动 window 并计算另一列中的不同值。 假设我有这个df dataframe:

date    customer
2020-01-01  A
2020-01-02  A
2020-01-02  B
2020-01-03  A
2020-01-03  C
2020-01-03  D
2020-01-04  E

我想按date列分组,创建两天的滚动 window 并计算列customer中的不同值。 预期的 output 将类似于:

date       distinct_customers
2020-01-01  NaN --> (first value)
2020-01-02  2.0 --> (distinct customers between 2020-01-01 and 2020-01-02: [A, B]) 
2020-01-03  4.0 --> (distinct customers between 2020-01-02 and 2020-01-03: [A, B, C, D])
2020-01-04  4.0 --> (distinct customers between 2020-01-03 and 2020-01-04: [A, C, D, E])

这似乎很容易,但我似乎没有找到任何直接的方法来实现这一点,我尝试过使用groupbyrolling 我没有找到解决此问题的其他帖子。 有人知道如何做到这一点吗? 提前非常感谢!

基于@Musulmon 的想法,这个班轮应该这样做:

pd.crosstab(df['date'], df['customer']).rolling(2).sum().clip(0,1).sum(axis=1)

谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM