How to print a grou...
Notifications
Clear all

How to print a groupby object

RSS

(@ganesh)
Noble Member
Joined: 2 years ago
Posts: 1362
11/05/2021 11:54 am

I want to print the result of grouping with Pandas.

I have a dataframe:

import pandas as pd

df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})

print(df)

A B

0 one 0

1 one 1

2 two 2

3 three 3

4 three 4

5 one 5

When printing after grouping by 'A' I have the following:

print(df.groupby('A'))

< pandas.core.groupby.DataFrameGroupBy object at 0x05416E90>

How can I print the dataframe grouped?

If I do:

print(df.groupby('A').head())

I obtain the dataframe as if it was not grouped:

A B

A

one 0 one 0

1 one 1

two 2 two 2

three 3 three 3

4 three 4

one 5 one 5

I was expecting something like:

A B

A

one 0 one 0

1 one 1

5 one 5

two 2 two 2

three 3 three 3

4 three 4


Quote
(@abhijith)
Noble Member
Joined: 2 years ago
Posts: 1350
11/05/2021 11:55 am

Simply do this:

grouped_df = df.groupby('A')

for key, item in grouped_df:

print(grouped_df.get_group(key), "\n\n")


ReplyQuote
Share:
Baidu