Arnold Klein
Arnold Klein

Reputation: 3086

To get only the first rows in Pandas data frame at different values of other attributes?

Given the following example data frame:

       summary              id
183       12.0              11
526       12.0              11
1036      14.0              11
1801      13.0              11
3003      12.0              11
14         6.0              17
177       11.0              17
511        8.0              17
1000       9.0              17
1767      10.0              17
4          6.0              18
287       12.0              18
618        9.0              18
1182      12.0              18
2035      13.0              18

How to get only first rows at different values of 'id' variable?

           summary              id
    183       12.0              11
    14         6.0              17
    4          6.0              18

Upvotes: 2

Views: 358

Answers (2)

EdChum
EdChum

Reputation: 394279

Use head on groupby object so you preserve the index:

In [62]:
df.groupby('id').head(1)

Out[62]:
     summary  id
183     12.0  11
14       6.0  17
4        6.0  18

Upvotes: 4

Kewl
Kewl

Reputation: 3417

use the groupby aggregate function, 'first'

df.groupby('id').first()

Upvotes: 1

Related Questions