w3resource

Grouping and Aggregating with multiple Index Levels in Pandas


8. Grouping and Aggregating with Multiple Index Levels

Write a Pandas program to perform grouping and aggregation operations using multiple index levels.

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'.
  • Sum the grouped data.
  • Print the result.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group data by two columns and create a multi-level index from the grouped result.
  • Write a Pandas program to perform groupby operations on a DataFrame with a hierarchical index and then aggregate with multiple functions.
  • Write a Pandas program to group data, set multiple index levels, and then unstack the result to obtain a pivot table.
  • Write a Pandas program to group data on multiple levels and compute aggregations that preserve the multi-index structure.

Python Code Editor:

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

Previous: Using GroupBy with Lambda functions in Pandas.
Next: Apply different functions to different columns with GroupBy.

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.