這是我正在使用的 df 的前 10 行: id user_id session_date mb_used0 1000_13 1000 2018-12-29 89.861 1000_204 1000 2018-12-31 0.002 1000_379 1000 2018-12-28 660.403 1000_413 1000 2018-12-26 270.994 1000_442 1000 2018-12-27 880.225 1001_0 1001 2018-08-24 284.686 1001_3 1001 2018-12-09 656.047 1001_4 1001 2018-11-04 16.978 1001_10 1001 2018-11-27 135.189 1001_15 1001 2018-12-13 761.92我的問題是:如何找到每月每個 user_id 的 mb_used 總量?這意味著我必須首先隔離每個 user_id,找出他們在同一個月內使用了多少行數據,然后將它們相加以獲得每個用戶的“每月使用的數據”。我可以使用數據透視表來查找每個用戶使用此代碼使用的總數據: internet_per_user = pd.pivot_table(internet, index = 'user_id', columns='mb_used',aggfunc='sum') 但我無法合并每月方面。對于上面發布的 10 行,我希望輸出看起來像這樣(手工計算):user_id Month mb_used1000 12 1901.471001 08 284.681001 12 1417.961001 11 152.15
1 回答

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
您需要對每個月的用戶 ID 進行分組并計算總和。您可以使用:
df['session_date'] = pd.to_datetime(df['session_date'], errors='coerce')
(df.groupby(['user_id', df['session_date'].dt.month])['mb_used']
.sum()
.reset_index())
user_id session_date mb_used
0 1000 12 1901.47
1 1001 8 284.68
2 1001 11 152.15
3 1001 12 1417.96
添加回答
舉報
0/150
提交
取消