Skip to content
Advertisement

Get value From Previous or Next Rows Based on Condition from two or more columns in Python

I am using Pandas Python to calculate timedelta between rows which when it uses previous or next rows is based on conditions.

My table is like this sampel table

I want to create timedelta column with this condition: it gets value from previous rows when STATUS > status_before and gets value from next rows when STATUS < status_after.

I tried several ways to do this, and mostly ended up with this error:

JavaScript

this one is one example of what I did:

JavaScript

Any solutions?

Advertisement

Answer

  • to get better quality answers always provide your sample data as text not images
  • np.where() allows you to use conditional logic in an assignment
  • your logic does not specify what value to use when condition is not met, so I’ve used REPORTDATE
JavaScript

output

REPORTDATE NAMA PELABUHAN STATUS ASAL IGNORED INSERTTIME status_after status_before timedelta
0 2021-06-18 00:00:00 WPP 571 di laut 1 PP Belawan 0 2021-06-24 09:26:35 0 nan 2021-06-18 00:00:00
1 2021-06-18 08:00:00 WPP 571 PP Belawan 0 di laut 0 2021-06-24 09:26:35 1 1 2021-06-18 00:00:00
2 2021-06-18 16:00:00 WPP 571 di laut 1 PP Belawan 0 2021-06-24 09:26:35 0 0 2021-06-18 16:00:00
3 2021-06-19 00:00:00 WPP 571 PP Belawan 0 di laut 0 2021-06-24 09:26:35 1 1 2021-06-18 16:00:00
4 2021-06-19 08:00:00 WPP 571 di laut 1 PP Belawan 0 2021-06-24 09:26:35 nan 0 2021-06-19 08:00:00
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement