[英]Conditional ffill based on another column
我試圖有條件地填充一個值,直到第二列遇到一個值,然后重置第一列值。 實際上,第一列是一個“開”開關,直到“關”開關(第二列)遇到一個值。 我還沒有一個使用 ffill 和 where 的工作示例。
示例輸入:
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
所需的 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
編輯:
處理基於另一列設置的值時會出現問題。 邏輯如下:開始應該為零,直到 R 列低於 25,然后為正,直到 R 列高於 80,並且循環應該重復。 然而,盡管標准不匹配,但在第 13 行 Start 莫名其妙地設置為 1。
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
嘗試:
df.loc[df['End'].shift().eq(0), 'Start'] = df['Start'].replace(0, np.nan).ffill().fillna(0).astype(int)
[出去]
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.