I have a pandas DataFrame
like following:
JavaScript
x
6
1
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
2
'value' : ["first","second","second","first",
3
"second","first","third","fourth",
4
"fifth","second","fifth","first",
5
"first","second","third","fourth","fifth"]})
6
I want to group this by ["id","value"]
and get the first row of each group:
JavaScript
1
19
19
1
id value
2
0 1 first
3
1 1 second
4
2 1 second
5
3 2 first
6
4 2 second
7
5 3 first
8
6 3 third
9
7 3 fourth
10
8 3 fifth
11
9 4 second
12
10 4 fifth
13
11 5 first
14
12 6 first
15
13 6 second
16
14 6 third
17
15 7 fourth
18
16 7 fifth
19
Expected outcome:
JavaScript
1
9
1
id value
2
1 first
3
2 first
4
3 first
5
4 second
6
5 first
7
6 first
8
7 fourth
9
I tried following, which only gives the first row of the DataFrame
. Any help regarding this is appreciated.
JavaScript
1
3
1
In [25]: for index, row in df.iterrows():
2
df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0]) .:
3
Advertisement
Answer
JavaScript
1
11
11
1
>>> df.groupby('id').first()
2
value
3
id
4
1 first
5
2 first
6
3 first
7
4 second
8
5 first
9
6 first
10
7 fourth
11
If you need id
as column:
JavaScript
1
10
10
1
>>> df.groupby('id').first().reset_index()
2
id value
3
0 1 first
4
1 2 first
5
2 3 first
6
3 4 second
7
4 5 first
8
5 6 first
9
6 7 fourth
10
To get n first records, you can use head():
JavaScript
1
16
16
1
>>> df.groupby('id').head(2).reset_index(drop=True)
2
id value
3
0 1 first
4
1 1 second
5
2 2 first
6
3 2 second
7
4 3 first
8
5 3 third
9
6 4 second
10
7 4 fifth
11
8 5 first
12
9 6 first
13
10 6 second
14
11 7 fourth
15
12 7 fifth
16