我希望分組日期國家和型別并將具有相同月份值的任何日期轉換為該月的第一天。
資料
country type date energy
US aa 8/5/2022 10
US aa 8/25/2022 1
US aa 8/2/2022 11
US bb 8/5/2022 55
US bb 8/15/2022 25
AUSTRALIA bb 9/15/2022 5
期望的
step 1: convert all dates to 1st of the month values
step 2: groupby country type and date sum energy
country type date energy
US aa 8/1/2022 22
US bb 8/1/2022 80
AUSTRALIA bb 9/1/2022 5
正在做
df.date - pd.offsets.MonthBegin(1)
df.groupby(['country','type','date'], as_index=False).agg({'energy': sum})
任何建議表示贊賞。
uj5u.com熱心網友回復:
試試這個pd.Grouper:
df.groupby(['country',
'type',
pd.Grouper(key='date', freq='MS')], sort=False)['energy'].sum().reset_index()
輸出:
country type date energy
0 US aa 2022-08-01 22
1 US bb 2022-08-01 80
2 AUSTRALIA bb 2022-09-01 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527132.html
