w3resource

Group by Multiple columns in Pandas


1. 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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group a DataFrame by two categorical columns and calculate the mean of a numeric column for each group.
  • Write a Pandas program to group data by multiple columns and then compute both the sum and count for each group simultaneously.
  • Write a Pandas program to group a dataset by multiple keys and filter out groups that do not meet a minimum group size threshold.
  • Write a Pandas program to group data by two columns and then pivot the grouped results to display multi-level headers.

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.



Follow us on Facebook and Twitter for latest update.