[英]Count occurrences in last 30 days with Pandas Dataframe
我有一個帶有 ID 列和日期列 (YYYY-MM-DD) 的 pandas Dataframe,
ID | 日期 |
---|---|
001 | 2022-01-01 |
001 | 2022-01-04 |
001 | 2022-02-07 |
002 | 2022-01-02 |
002 | 2022-01-03 |
002 | 2022-01-28 |
如圖所示,日期字段中可能存在間隙。 我想要一個新列“occurrences_last_month”,它計算上個月(30 天)中每個 ID 的出現次數。
想法是添加一個新列,其中包含以下 output,
ID | 日期 | Occurrences_last_month |
---|---|---|
001 | 2022-01-01 | 0 |
001 | 2022-01-04 | 1 |
001 | 2022-02-07 | 0 |
002 | 2022-01-02 | 0 |
002 | 2022-01-03 | 1 |
002 | 2022-01-28 | 2 |
例如,在 ID 001 的情況下:
我嘗試使用 datetime.timedelta 來計算一個新列“date_previous_month”,但我無法從那里計算出我需要的內容,我嘗試使用 count() 但未能獲得我需要的內容。
第一個想法是每個組使用Rolling.count
並刪除由ID
創建的第一級:
df = df.set_index('Date')
df['Ocurrences_last_month'] = (df.groupby('ID')
.rolling('30D')
.count().sub(1).droplevel(0).astype(int))
print (df)
ID Ocurrences_last_month
Date
2022-01-01 1 0
2022-01-04 1 1
2022-02-07 1 0
2022-01-02 2 0
2022-01-03 2 1
2022-01-28 2 2
編輯:如果可能的重復值創建Series
並由 DataFrame.join 分配給原始DataFrame.join
:
s = df.groupby('ID').rolling('30D', on='Date')['Date'].count().sub(1).astype(int)
df = df.join(s.rename('Ocurrences_last_month'), on=['ID','Date'])
print (df)
ID Date Ocurrences_last_month
0 1 2022-01-01 0
1 1 2022-01-04 1
2 1 2022-02-07 0
3 2 2022-01-02 0
4 2 2022-01-03 1
5 2 2022-01-28 2
來自評論的替代解決方案:
df = df.merge(s.rename('Ocurrences_last_month'), on=['ID','Date'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.