Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I reference the line above a particular line in a pandas dataframe?

I have the following pandas dataframe:

issue_stat     timestamp   state
    0          11:00:00     hi
    1          12:40:00     lo
    9          13:00:00     av
    3          15:00:00     hi 
    8          18:00:00     hi
    4          20:00:00     lo

I want to map the state of the line above timestamp=18:00:00 to jazz. I MUST use the timestamp=18:00:00 in my code. How would I do this?

I know how to map the state of timestamp=18:00:00:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dataframe.loc[dataframe['timestamp'] == '18:00:00', 'state'] = whatever

But I am having difficult pointing to the line above it. Again I emphasise, I MUST reference the timestamp = 18:00:00 in my code.

So the output looks like this:

issue_stat     timestamp   state
     0          11:00:00     hi
     1          12:40:00     lo
     9          13:00:00     av
     3          15:00:00    jazz 
     8          18:00:00     hi
     4          20:00:00     lo

>Solution :

The shift() method moves the series in either direction. So to set the state of the cell where the following timestamp is 18:00:

df.loc[df["timestamp"].shift(-1) == '18:00:00', 'state'] = 'jazz'

Produces:

   issue_stat           timestamp    state
0           0            11:00:00       hi
1           1            12:40:00       lo
2           9            13:00:00       av
3           3            15:00:00     jazz
4           8            18:00:00       hi
5           4            20:00:00       lo
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading