w3resource

Grouping and Aggregating with multiple Index Levels in Pandas


Pandas Advanced Grouping and Aggregation: Exercise-8 with Solution


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.

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.