I'm trying to conditionally ffill a value until a second column encounters a value and then reset the first column value. Effectively the first column is an 'on' switch until the 'off' switch (second column) encounters a value. I've yet to have a working example using ffill and where.
Example input:
Index Start End
0 0 0
1 0 0
2 1 0
3 0 0
4 0 0
5 0 0
6 0 1
7 0 0
8 1 0
9 0 0
10 0 0
11 0 0
12 0 1
13 0 1
14 0 0
Desired output:
Index Start End
0 0 0
1 0 0
2 1 0
3 1 0
4 1 0
5 1 0
6 1 1
7 0 0
8 1 0
9 1 0
10 1 0
11 1 0
12 1 1
13 0 1
14 0 0
EDIT:
There are issues when dealing with values set based on another column. The logic is as follows: Start should be zero until R column is below 25, then positive until R column is above 80 and the cycle should repeat. Yet on row 13 Start is inexplicably set 1 despite not matching criteria.
df = pd.DataFrame(np.random.randint(0, 100, size=100), columns=['R'])
df['Start'] = np.where((df.R < 25), 1, 0)
df['End'] = np.where((df.R > 80), 1, 0)
df.loc[df['End'].shift().eq(0), 'Start'] = df['Start'].replace(0, np.nan).ffill().fillna(0).astype(int)
R Start End
0 58 0 0
1 98 0 1
2 91 0 1
3 69 0 0
4 55 0 0
5 57 0 0
6 64 0 0
7 75 0 1
8 78 0 1
9 90 0 1
10 24 1 0
11 89 1 1
12 36 0 0
13 70 **1** 0
Try:
df.loc[df['End'].shift().eq(0), 'Start'] = df['Start'].replace(0, np.nan).ffill().fillna(0).astype(int)
[out]
Start End
0 0 0
1 0 0
2 1 0
3 1 0
4 1 0
5 1 0
6 1 1
7 0 0
8 1 0
9 1 0
10 1 0
11 1 0
12 1 1
13 0 1
14 0 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.