The data below is based on GPS coordinates of a van, whether the ignition was on/off, and how far the van was from a target location at a given time. I want to determine whether a van was at or near a location (<300), whether the ignition was turned off, and if both conditions are true, the time duration of the stay.
In the example below, I visualize rows 1-4 as being "grouped" together since they are consecutive rows where the distance was <300. Row 5 is "grouped" on its own since it was >300, and rows 6-8 are "grouped" together since they are consecutive rows with distance <300.
Accordingly, since the ignition was turned off in rows 1-4, I want to calculate the time duration (since the van "stopped" at the location for a given amount of time). However, the other two groups (row 5 and rows 6-8) should not have a time duration calculation since the ignition was never turned off in those groupings.
df
AcctID On_Off Distance Timestamp
123 On 230 12:00
123 On 30 12:02
123 Off 29 12:05
123 Off 35 12:10
123 On 3000 12:13
123 On 100 12:20
123 On 95 12:22
123 On 240 12:28
I'm able to classify whether the Distance is less than 300 (Within_Distance
), but determining whether the ignition was off for at least one of the rows in the grouping has me stumped. Here's what the final dataframe should look like:
df['Within_Distance'] = np.where(df['Distance']<300, "Yes", "No")
df
AcctID On_Off Distance Timestamp Within_Distance Was_Off Within_Distance_and_Was_Off
123 On 230 12:20 Yes Yes Yes
123 On 30 12:02 Yes Yes Yes
123 Off 29 12:05 Yes Yes Yes
123 Off 35 12:10 Yes Yes Yes
123 On 3000 12:13 No No No
123 On 100 12:20 Yes No No
123 On 95 12:22 Yes No No
123 On 240 12:28 Yes No No
Thanks in advance!