w3resource

Group by Multiple columns in Pandas

Pandas Advanced Grouping and Aggregation: Exercise-1 with Solution

Grouping by Multiple columns:
Write a Pandas program to group data by multiple columns to perform complex data analysis and aggregations.

Sample Solution:

Python Code :

import pandas as pd
# Sample DataFrame
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
        'Type': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
        'Value': [1, 2, 3, 4, 5, 6]}

df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and 'Type'
print("\nGroup by 'Category' and 'Type':")
grouped = df.groupby(['Category', 'Type']).sum()
print(grouped)

Output:

Sample DataFrame:
  Category Type  Value
0        A    X      1
1        A    Y      2
2        B    X      3
3        B    Y      4
4        C    X      5
5        C    Y      6

Group by 'Category' and 'Type':
               Value
Category Type       
A      X         1
       Y         2
B      X         3
       Y         4
C      X         5
       Y         6

Explanation:

  • Import pandas.
  • Create a sample DataFrame.
  • Group by 'Category' and 'Type' columns.
  • Sum the grouped data.
  • Print the result.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Advanced Grouping and Aggregation Exercises Home.
Next: Apply Multiple Aggregations on Grouped Data in Pandas.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/advanced-grouping-and-aggregation/group-by-multiple-columns-in-pandas.php