w3resource

Combining GroupBy with Transform in Pandas

Pandas Advanced Grouping and Aggregation: Exercise-11 with Solution

Combining GroupBy with Transform:
Write a Pandas program to combine GroupBy with Transform to perform complex data transformations on grouped data.

Sample Solution:

Python Code :

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

df = pd.DataFrame(data)
print("Sample DataFrame:")
print(df)
# Group by 'Category' and transform by calculating the mean
print("\nGroup by 'Category' and transform by calculating the mean:")
transformed = df.groupby('Category').transform('mean')
print(transformed)

Output:

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

Group by 'Category' and transform by calculating the mean:
   Value
0    1.5
1    1.5
2    3.5
3    3.5
4    5.5
5    5.5

Explanation:

  • Import pandas.
  • Create a sample DataFrame.
  • Group by 'Category'.
  • Transform by calculating the mean for each group.
  • Print the transformed DataFrame.

Python Code Editor:

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

Previous: Using named Aggregations in Pandas GroupBy.
Next: GroupBy and Apply different functions using a Dictionary 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://198.211.115.131/python-exercises/pandas/advanced-grouping-and-aggregation/combining-groupby-with-transform-in-pandas.php