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?
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?
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')