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
x
2
1
The truth value of a Series is ambiguous. Use a.empty, a.bool(),a.item(), a.any() or a.all().
2
this one is one example of what I did:
JavaScript
1
3
1
if db.STATUS == 0 and db.status_before == 1:
2
db.delta = db['REPORTDATE'].shift()
3
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
1
21
21
1
import numpy as np
2
3
df = pd.DataFrame({"REPORTDATE":pd.date_range("2021-06-18", freq="8h", periods=5), "NAMA":["WPP 571"]*5,
4
"PELABUHAN":(["PP Belawan","di laut"]*3)[1:6], "STATUS":([1,0]*3)[0:5],
5
"ASAL":(["PP Belawan","di laut"]*3)[0:5], "IGNORED":[0]*5,
6
"INSERTTIME":[pd.to_datetime("2021-06-24 09:26:35")]*5})
7
8
9
10
(
11
df.assign(
12
status_after=df["STATUS"].shift(-1), status_before=df["STATUS"].shift()
13
).assign(
14
timedelta=lambda d: np.where(
15
(d.STATUS == 0) & (d["status_before"] == 1),
16
d["REPORTDATE"].shift(),
17
d["REPORTDATE"],
18
)
19
)
20
)
21
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 |