簡體   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