Let's say I have a data frame named df as below in Pandas :
id x y
1 10 A
2 12 B
3 10 B
4 4 C
5 9 A
6 15 A
7 6 B
Now I would like to group data by column y and get mean of 2 largest values (x) of each group, which would look something like that
y
A (10+15)/2 = 12.5
B (12 + 10)/2 = 11
C 4
If I try with df.groupby('y')['x'].nlargest(2), I get
y id
A 1 10
6 15
B 2 12
3 10
C 4 4
which is of type pandas.core.series.Series. So when I do df.groupby('y')[x].nlargest(2).mean() I get mean of all numbers instead of 3 means, one for each group. At the end I would like to plot the results where groups would be on the x axis and means on y axis, so I'm guessing I should get rid of column 'id' as well?
Anyone knows how to solve this one? Thank you for help!
df.groupby('y')['x'].nlargest(2).mean(level=0)
Out:
y
A 12.5
B 11.0
C 4.0
Name: x, dtype: float64
Note that this is grouping by 'y' two times (mean(level=0) is another groupby but it is done on an index so it is faster). groupby.apply might be more efficient based on the number of groups as it requires grouping only once in this particular situation.
df.groupby('y')['x'].apply(lambda ser: ser.nlargest(2).mean())
Out:
y
A 12.5
B 11.0
C 4.0
Name: x, dtype: float64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With