我有一個記錄用戶的資料框,一個標簽,以及他們的開始和結束日期被標記為例如
| 用戶 | 標簽 | 開始日期 | 結束日期 |
|---|---|---|---|
| 1 | X | 2018-01-01 | 2018-10-01 |
| 2 | X | 2019-05-10 | 2020-01-01 |
| 3 | 是的 | 2019-04-01 | 2022-04-20 |
| 1 | b | 2018-10-01 | 2020-05-08 |
ETC
其中每一行是給定用戶和標簽的;一個用戶針對不同的標簽多次出現
我想為每個標簽獲取每個月的用戶計數,例如:
| 日期 | count_label_x | count_label_y | count_label_b | count_label_ |
|---|---|---|---|---|
| 2018-01 | 10 | 0 | 20 | 5 |
| 2018-02 | 2 | 5 | 15 | 3 |
| 2018-03 | 20 | 6 | 8 | 3 |
ETC
例如,對于上表的第一個條目,該用戶應在其開始日期和結束日期之間的每個月計算一次。問題歸結為這一點,因為我只有幾個標簽,我可以一個一個過濾標簽并為每個標簽生成一個輸出。但是如何在給定時間間隔的情況下檢查和計算用戶數?
謝謝
uj5u.com熱心網友回復:
您可以使用date_range組合 withto_period來生成活動月份,然后pivot_table使用 withaggfunc='nunique'來聚合唯一用戶(如果要計算重復用戶 use aggfunc='count'):
out = (df
.assign(period=[pd.date_range(a, b, freq='M').to_period('M')
for a,b in zip(df['start_date'], df['end_date'])])
.explode('period')
.pivot_table(index='period', columns='label', values='user',
aggfunc='nunique', fill_value=0)
)
輸出:
label b x y
period
2018-01 0 1 0
2018-02 0 1 0
2018-03 0 1 0
2018-04 0 1 0
2018-05 0 1 0
...
2021-12 0 0 1
2022-01 0 0 1
2022-02 0 0 1
2022-03 0 0 1
處理 NaT
如果您有相同的開始/結束并想計算該值:
out = (df
.assign(period=[pd.date_range(a, b, freq='M').to_period('M')
for a,b in zip(df['start_date'], df['end_date'])])
.explode('period')
.assign(period=lambda d: d['period'].fillna(d['start_date'].dt.to_period('M')))
.pivot_table(index='period', columns='label', values='user',
aggfunc='nunique', fill_value=0)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/522211.html
標籤:熊猫日期日期范围
