我看大部分以前問過的問題,但沒能找到我的問題的答案的總和:熊貓:集團由兩列得到另一列
我有以下data.frame
id year month score num_attempts
0 483625 2010 01 50 1
1 967799 2009 03 50 1
2 213473 2005 09 100 1
3 498110 2010 12 60 1
5 187243 2010 01 100 1
6 508311 2005 10 15 1
7 486688 2005 10 50 1
8 212550 2005 10 500 1
10 136701 2005 09 25 1
11 471651 2010 01 50 1
我希望得到以下數據幀
year month sum_score sum_num_attempts
2009 03 50 1
2005 09 125 2
2010 12 60 1
2010 01 200 2
2005 10 565 3
這裏是我的嘗試:
sum_df = df.groupby(by=['year','month'])['score'].sum()
但這看起來效率和正確。如果我有多個列需要聚合,這看起來像一個非常昂貴的電話。例如,如果我有另一列num_attempts
,只想按年份總和作爲分數。
你能否解釋一下爲什麼你認爲這是一個廣闊的電話,如果你想保持它在集團化運作,你會用'num_attempts'做什麼呢? – Boud
@MaxU不確定我是否理解使用'as_index = False,那是幹什麼的? –
抱歉我的第一條評論 - 我誤解了你。有什麼問題:'df.groupby(['year','month'])[['score','num_attempts']]。sum()'或'df.groupby(['year','month' ])。agg({'score':'sum','num_attempts':'max'})'? – MaxU