Suppose I have pandas DataFrame like this:
JavaScript
x
2
1
df = pd.DataFrame({'id':[1,1,1,2,2,2,2,3,4], 'value':[1,2,3,1,2,3,4,1,1]})
2
which looks like:
JavaScript
1
11
11
1
id value
2
0 1 1
3
1 1 2
4
2 1 3
5
3 2 1
6
4 2 2
7
5 2 3
8
6 2 4
9
7 3 1
10
8 4 1
11
I want to get a new DataFrame with top 2 records for each id, like this:
JavaScript
1
8
1
id value
2
0 1 1
3
1 1 2
4
3 2 1
5
4 2 2
6
7 3 1
7
8 4 1
8
I can do it with numbering records within group after groupby
:
JavaScript
1
2
1
dfN = df.groupby('id').apply(lambda x:x['value'].reset_index()).reset_index()
2
which looks like:
JavaScript
1
11
11
1
id level_1 index value
2
0 1 0 0 1
3
1 1 1 1 2
4
2 1 2 2 3
5
3 2 0 3 1
6
4 2 1 4 2
7
5 2 2 5 3
8
6 2 3 6 4
9
7 3 0 7 1
10
8 4 0 8 1
11
then for the desired output:
JavaScript
1
2
1
dfN[dfN['level_1'] <= 1][['id', 'value']]
2
Output:
JavaScript
1
8
1
id value
2
0 1 1
3
1 1 2
4
3 2 1
5
4 2 2
6
7 3 1
7
8 4 1
8
But is there more effective/elegant approach to do this? And also is there more elegant approach to number records within each group (like SQL window function row_number()).
Advertisement
Answer
Did you try
JavaScript
1
2
1
df.groupby('id').head(2)
2
Output generated:
JavaScript
1
9
1
id value
2
id
3
1 0 1 1
4
1 1 2
5
2 3 2 1
6
4 2 2
7
3 7 3 1
8
4 8 4 1
9
(Keep in mind that you might need to order/sort before, depending on your data)
EDIT: As mentioned by the questioner, use
JavaScript
1
2
1
df.groupby('id').head(2).reset_index(drop=True)
2
to remove the MultiIndex and flatten the results:
JavaScript
1
8
1
id value
2
0 1 1
3
1 1 2
4
2 2 1
5
3 2 2
6
4 3 1
7
5 4 1
8