Group by month and divide the average of one column by the average of the other?

Viewed 34

I have two columns A and B. I want to divide the mean of A by the mean of B.

df['Test']= df.groupby('Month').apply(lambda x: df['A'].mean().astype(float)/df['B'].mean().astype(float))

Help me, where is the error?

1 Answers

The issue is likely that you define your lambda with x as parameter but then use df. It should rather be:

df.groupby('Month').apply(lambda x: x['A'].mean()/x['B'].mean())

NB. converting to float after computing the mean makes little sense, should you convert before?

You can use instead:

g = df.groupby('Month')
out = g['A'].mean()/g['B'].mean()

or for a transformation:

g = df.groupby('Month')
df['Test'] = g['A'].transform('mean')/g['B'].transform('mean')
Related