Python按组分类,然后某些列保留第一个,其他列保留最后一个。

4

我有一个看起来像这样的数据框:

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

由于在城市1中的人物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

每一行都有唯一的键{城市ID, 个人ID}。 我尝试过 df = df.groupby['cityid','personid'].['yearstart','momthstart'].first()['yearend, monthend'].last() 但出现了错误信息。
请问如何修复呢?谢谢!
1个回答

2
您可以使用agg
(df.groupby(['cityid','persionid'])
   .agg({'yearstart':'first',
         'monthstart':'first',
         'yearend':'last',
         'monthend':'last'})
)
  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接