close

How to GroupBy a Dataframe in Pandas and keep Columns

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to GroupBy a Dataframe in Pandas and keep Columns in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to GroupBy a Dataframe in Pandas and keep Columns?

  1. How to GroupBy a Dataframe in Pandas and keep Columns?

    I think as_index=False should do the trick.
    df.groupby(['Name','Type','ID'], as_index=False).count()

  2. GroupBy a Dataframe in Pandas and keep Columns

    I think as_index=False should do the trick.
    df.groupby(['Name','Type','ID'], as_index=False).count()

Method 1

You want the 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 your case the ‘Name’, ‘Type’ and ‘ID’ cols match in values so we can groupby on these, call count and then reset_index.

An alternative approach would be to add the ‘Count’ column using transform and then 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

Method 2

I think as_index=False should do the trick.

df.groupby(['Name','Type','ID'], as_index=False).count()

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read