I have sample dataframe as follows
I just want to mark all the rows where id == 11 preeceded by 2. If the id ==11 and does not preeced by 2 in the immediate rows I want to mark it as 0
Home" Date Time id Appliance Banana expected_output output_from the code
1 1/21/2017 1:30:00 11 Apple 0 1 1
2 1/21/2017 1:45:00 11 Apple 0 1 1
3 1/21/2017 2:00:00 11 Apple 0 1 1
4 1/21/2017 2:15:00 2 Banana 1 1 0
5 1/21/2017 2:30:00 2 Banana 0 0 0
6 1/21/2017 2:45:00 0 Orange 0 0 0
7 1/21/2017 3:00:00 1 Peach 0 0 0
8 1/21/2017 3:15:00 1 Peach 0 0 0
9 1/21/2017 3:30:00 3 Pineapple 0 0 0
10 1/21/2017 3:45:00 3 Pineapple 0 0 0
11 1/21/2017 4:00:00 11 Apple 0 0 1
12 1/21/2017 4:15:00 11 Apple 0 0 1
13 1/21/2017 4:30:00 11 Apple 0 0 1
14 1/21/2017 4:45:00 0 Orange 0 0 0
15 1/22/2017 3:30:00 1 Peach 0 0 0
16 1/22/2017 3:45:00 1 Peach 0 0 0
17 1/22/2017 4:00:00 3 Pineapple 0 0 0
18 1/22/2017 4:15:00 3 Pineapple 0 0 0
19 1/22/2017 4:30:00 11 Apple 0 1 1
20 1/22/2017 4:45:00 11 Apple 0 1 1
21 1/22/2017 5:00:00 11 Apple 0 1 1
22 1/22/2017 5:15:00 2 Banana 1 1 0
23 1/22/2017 5:30:00 2 Banana 1 0 0
what I have achieved so far
df['Banana'] = np.where((df['id']==2) & (df['id'].shift(+1)==11), 1,
0)
formatted_df['output_from the code'] = np.where((df['id']==11) & (df['id'].shift(-1)==2), 1,
np.where((df['id']==11) & (df['id'].shift(-1)==11), 1,
0))
is there a way to write np.where based on previous row