Wednesday 24 April 2024

Pandas: Print the content of a group by data

We can iterate over the content of group by data using for loop.

Example

for group_name, group_data in group_by_object:
    print("Group Name:", group_name)
    print(group_data)

 

Find the below working application.

 

print_group_by_data.py
import pandas as pd

# Print the content of DataFrameGroupBy object
def print_group_by_result(group_by_object):
    for group_name, group_data in group_by_object:
        print("Group Name:", group_name)
        print(group_data)
        print()


# Create a sample DataFrame
data = { 'Name': ['Krishna', 'Chamu', 'Joel', 'Gopi', 'Sravya', "Raj"],
         'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Male', 'Female', 'Male'],
         'Weight': [74, 58, 85, 87, 63, 79]}

df = pd.DataFrame(data)
print(df)

group_by_city = df.groupby('City')
print('\nGroup by city is')
print('type of group_by_city is : ', type(group_by_city))
print_group_by_result(group_by_city)

Output

      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
1    Chamu   25    Chennai  Female      58
2     Joel   29  Hyderabad    Male      85
3     Gopi   41  Hyderabad    Male      87
4   Sravya   52  Bangalore  Female      63
5      Raj   23    Chennai    Male      79

Group by city is
type of group_by_city is :  <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
Group Name: Bangalore
      Name  Age       City  Gender  Weight
0  Krishna   34  Bangalore    Male      74
4   Sravya   52  Bangalore  Female      63

Group Name: Chennai
    Name  Age     City  Gender  Weight
1  Chamu   25  Chennai  Female      58
5    Raj   23  Chennai    Male      79

Group Name: Hyderabad
   Name  Age       City Gender  Weight
2  Joel   29  Hyderabad   Male      85
3  Gopi   41  Hyderabad   Male      87




  

Previous                                                 Next                                                 Home

No comments:

Post a Comment