Aggregation over Partition in pandas

You can use pandas transform() method for within group aggregations like “OVER(partition by …)” in SQL:

import pandas as pd
import numpy as np

#create dataframe with sample data
df = pd.DataFrame({'group':['A','A','A','B','B','B'],'value':[1,2,3,4,5,6]})

#calculate AVG(value) OVER (PARTITION BY group)
df['mean_value'] = df.groupby('group').value.transform(np.mean)

df:
group   value   mean_value
A       1       2
A       2       2
A       3       2
B       4       5
B       5       5
B       6       5

Leave a Comment