python - How to GroupBy a Dataframe in Pandas and keep Columns -


given dataframe logs uses of books this:

name   type   id book1  ebook  1 book2  paper  2 book3  paper  3 book1  ebook  1 book2  paper  2 

i need count of books, keeping other columns , this:

name   type   id    count book1  ebook  1     2 book2  paper  2     2 book3  paper  3     1 

how can done?

thanks!

you want following:

in [20]: df.groupby(['name','type','id']).count().reset_index()  out[20]:     name   type  id  count 0  book1  ebook   1      2 1  book2  paper   2      2 2  book3  paper   3      1 

in case 'name', 'type' , 'id' cols match in values can groupby on these, call count , reset_index.

an alternative approach add 'count' column using transform , call drop_duplicates:

in [25]: df['count'] = df.groupby(['name'])['id'].transform('count') df.drop_duplicates()  out[25]:     name   type  id  count 0  book1  ebook   1      2 1  book2  paper   2      2 2  book3  paper   3      1 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -