How to GroupBy a Dataframe in Pandas and keep Columns

前端 未结 3 2121
甜味超标
甜味超标 2020-12-07 14:09

given a dataframe that logs uses of some books like this:

Name   Type   ID
Book1  ebook  1
Book2  paper  2
Book3  paper  3
Book1  ebook  1
Book2  paper  2
         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 15:02

    If you have many columns in a df it makes sense to use df.groupby(['foo']).agg(...), see here. The .agg() function allows you to choose what to do with the columns you don't want to apply operations on. If you just want to keep them, use .agg({'col1': 'first', 'col2': 'first', ...}. Instead of 'first', you can also apply 'sum', 'mean' and others.

提交回复
热议问题