我有一个看起来像的数据框:
cityid personid yearstart monthstart yearend monthend
1 1 2000 01 2001 02
1 1 2001 02 2001 10
1 2 2001 10 2002 10
2 3 2000 01 2002 12
2 4 2005 08 2006 12
自 person 1
在 city 1
连续有两个术语,我想合并这两行并得到:cityid personid yearstart monthstart yearend monthend
1 1 2000 01 2001 10
1 2 2001 10 2002 10
2 3 2000 01 2002 12
2 4 2005 08 2006 12
所以每一行都有一个唯一的键 {cityid, personid}。我试过
df = df.groupby['cityid','personid'].['yearstart','momthstart'].first()['yearend, monthend'].last()
但收到错误消息。我能问一下如何解决这个问题吗?谢谢!
最佳答案
您可以使用 agg
:
(df.groupby(['cityid','persionid'])
.agg({'yearstart':'first',
'monthstart':'first',
'yearend':'last',
'monthend':'last'})
)
关于python groupby 然后一些列先保留其他列最后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63728086/