extract last row of each shift(day& night) from dataframe using python

Viewed 56

Hi i want to extract last row for each Shift(day & night) from dataframe.sample of the dataframe is given below.

Shift   Mark    value name
Night   34      122    mark
Night   14      1224   gomes
Night   24      1212   nick
Day     34      34     jonas
Day     34      12     ricky
Day     34      0      nick
Night   34      13     ricky
Night   34      12     gomes
Night   34      1200   martin
Day     24      34     jonas
Day     64      12     ricky
Day     664     1      Hayden

The expected output is given below:

Shift   Mark    value name
Night   24      1212   nick
Day     34      0      nick
Night   34      1200   martin
Day     664     1      Hayden

I tried using group by but didn't able to get desired output. What I want to do is just considering the Shift column, when the Shift changes(Night to day or Day to night), get the last row for each shift.

1 Answers

Use Series.ne for not equal like != and test if match shifted values by Series.shift, last test in boolean indexing:

df = df[df['Shift'].ne(df['Shift'].shift(-1))]
print (df)
    Shift  Mark  value    name
2   Night    24   1212    nick
5     Day    34      0    nick
8   Night    34   1200  martin
11    Day   664      1  Hayden
Related