Suppose I have pandas DataFrame like this:
id value
0 1 1
1 1 2
2 1 3
3 2 4
4 2 3
5 2 2
6 2 1
7 3 1
I'd like to compute the mean per id over the first 2 records and and append the resulte as new column like:
id value top_2_mean
0 1 1 1.5
1 1 2 1.5
2 1 3 1.5
3 2 4 3.5
4 2 3 3.5
5 2 2 3.5
6 2 1 3.5
7 3 1 1
Use
GroupBy.transformwith lambda function for first2values and mean: