我试图在Pandas中计算一个日期列上的滚动窗口,并计算另一列中的不同值。假设我有这个df
数据框:
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
列分组,创建一个两天的滚动窗口,并计算customer
列中的不同值。预期的输出将类似于:
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])
这似乎很容易,但是我似乎没有找到任何简单的方法来实现这一目标,我尝试使用groupby
或rolling
。我找不到其他帖子可以解决此问题。有人知道该怎么做吗?提前非常感谢!
答案 0 :(得分:1)
基于@Musulmon的想法,这只衬纸应该做到这一点:
pd.crosstab(df['date'], df['customer']).rolling(2).sum().clip(0,1).sum(axis=1)
谢谢!