我有一個數據框,如下所示:cityid personid yearstart monthstart yearend monthend 1 1 2000 01 2001 021 1 2001 02 2001 101 2 2001 10 2002 102 3 2000 01 2002 122 4 2005 08 2006 12由于person 1incity 1連續有兩個術語,我想將這兩行組合起來并得到:cityid personid yearstart monthstart yearend monthend 1 1 2000 01 2001 101 2 2001 10 2002 102 3 2000 01 2002 122 4 2005 08 2006 12所以每一行都有一個唯一的鍵 {cityid, personid}。我試過df = df.groupby['cityid','personid'].['yearstart','momthstart'].first()['yearend, monthend'].last()但收到錯誤消息。我能問一下如何解決這個問題嗎?謝謝!
1 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
您可以使用agg:
(df.groupby(['cityid','persionid'])
.agg({'yearstart':'first',
'monthstart':'first',
'yearend':'last',
'monthend':'last'})
)
添加回答
舉報
0/150
提交
取消