繁体   English   中英

python groupby 然后一些列先保留其他列最后

[英]python groupby then some columns keep first others keep last

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

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

由于city 1 person 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'})
)
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM