Label the first element in each groupby

Viewed 137

I have a data frame that looks like the following

df = pd.DataFrame({'group':[1,1,2,2,2],'time':[1,2,3,4,5],'C':[6,7,8,9,10]})
    group   time    C
0   1       1       6
1   1       2       7
2   2       3       8
3   2       4       9
4   2       5       10

and I'm looking to label the first element (in terms of time) in each group as True, i.e.:

    group   time    C   first_in_group
0   1       1       6   True
1   1       2       7   False
2   2       3       8   True
3   2       4       9   False
4   2       5       10  False

I tried several combinations of groupby, first but did not manage to achieve what I wanted.

Is there an elegant way to do it in Pandas?

1 Answers

Use duplicated:

df['first_in_group'] = ~df.group.duplicated()
OUTPUT:
   group  time   C  first_in_group
0      1     1   6            True
1      1     2   7           False
2      2     3   8            True
3      2     4   9           False
4      2     5  10           False

NOTE: Do the sorting 1st (if required).

df = df.sort_values(['group', 'time'])
Related