Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

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

2 Answers

0 votes
by (41.4k points)
edited by

Simply do this:

grouped_df = df.groupby('A')

for key, item in grouped_df:

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

If you are interested in learning Data Science then watch this video:

0 votes
by (3.1k points)

Groupby is generally used for grouping the stats of similarly categories to implement that we need to first 

1. Convert to DataFrame Using Aggregations 

Use an aggregation method to display results, such as.sum(),.mean(), etc. 

 

import pandas as pd 

 

# Sample data 

data = {'Category': ['A', 'A', 'B', 'B'], 'Value': [10, 20, 30, 40]} 

df = pd.DataFrame(data) 

 

# Group by 'Category' and aggregate 

grouped = df.groupby('Category').sum() 

print(grouped) 

2. Iterate Over Groups 

Iterate over each group to print individual group data. 

 

 for name, group in df.groupby('Category'): 

    print(f"Group: {name}") 

    print(group) 

3. To List or Dictionary 

You can also convert groups to a list or dictionary to print. 

grouped_dict = dict(tuple(df.groupby('Category'))) 

print(grouped_dict) 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...