[英]Pandas groupby and sum with the current month
這是我正在使用的 df 的前 10 行:
id user_id session_date mb_used
0 1000_13 1000 2018-12-29 89.86
1 1000_204 1000 2018-12-31 0.00
2 1000_379 1000 2018-12-28 660.40
3 1000_413 1000 2018-12-26 270.99
4 1000_442 1000 2018-12-27 880.22
5 1001_0 1001 2018-08-24 284.68
6 1001_3 1001 2018-12-09 656.04
7 1001_4 1001 2018-11-04 16.97
8 1001_10 1001 2018-11-27 135.18
9 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_used
1000 12 1901.47
1001 08 284.68
1001 12 1417.96
1001 11 152.15
您需要對每個月的用戶 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.