Pandas:当条件匹配时,从另一列上面的行复制值
Pandas: copy value from row above of another column when condition match
当“event”列的值不为 0,并且“input1”列上方的行的值为 5 时,我需要复制“label”列上方行的值。
我现在拥有的:
input1 input2 input3 event label
0 0 0 0 0
5 5 0 0 2
5 5 0 0 2
0 0 0 24 0
0 0 0 0 0
5 0 5 0 3
5 0 5 0 3
5 0 5 0 3
0 0 0 25 0
0 0 0 0 0
我需要发生的事情:
input1 input2 input3 event label marker
0 0 0 0 0 0
5 5 0 0 2 0
5 5 0 0 2 0
0 0 0 24 0 2
0 0 0 0 0 0
5 0 5 0 3 0
5 0 5 0 3 0
5 0 5 0 3 0
0 0 0 25 0 3
0 0 0 0 0 0
您可以使用布尔掩码 eq
/ne
, and shift
to get the previous values, then select with where
:
# is the previous input1 equal to 5?
m1 = df['input1'].shift().eq(5)
# is event not 0?
m2 = df['event'].ne(0)
# get the previous label if both conditions are true, else 0
df['marker'] = df['label'].shift(fill_value=0).where(m1&m2, 0)
# OR
# df['marker'] = df['label'].shift().where(m1&m2, 0).convert_dtypes()
输出:
input1 input2 input3 event label marker
0 0 0 0 0 0 0
1 5 5 0 0 2 0
2 5 5 0 0 2 0
3 0 0 0 24 0 2
4 0 0 0 0 0 0
5 5 0 5 0 3 0
6 5 0 5 0 3 0
7 5 0 5 0 3 0
8 0 0 0 25 0 3
9 0 0 0 0 0 0
当“event”列的值不为 0,并且“input1”列上方的行的值为 5 时,我需要复制“label”列上方行的值。
我现在拥有的:
input1 input2 input3 event label
0 0 0 0 0
5 5 0 0 2
5 5 0 0 2
0 0 0 24 0
0 0 0 0 0
5 0 5 0 3
5 0 5 0 3
5 0 5 0 3
0 0 0 25 0
0 0 0 0 0
我需要发生的事情:
input1 input2 input3 event label marker
0 0 0 0 0 0
5 5 0 0 2 0
5 5 0 0 2 0
0 0 0 24 0 2
0 0 0 0 0 0
5 0 5 0 3 0
5 0 5 0 3 0
5 0 5 0 3 0
0 0 0 25 0 3
0 0 0 0 0 0
您可以使用布尔掩码 eq
/ne
, and shift
to get the previous values, then select with where
:
# is the previous input1 equal to 5?
m1 = df['input1'].shift().eq(5)
# is event not 0?
m2 = df['event'].ne(0)
# get the previous label if both conditions are true, else 0
df['marker'] = df['label'].shift(fill_value=0).where(m1&m2, 0)
# OR
# df['marker'] = df['label'].shift().where(m1&m2, 0).convert_dtypes()
输出:
input1 input2 input3 event label marker
0 0 0 0 0 0 0
1 5 5 0 0 2 0
2 5 5 0 0 2 0
3 0 0 0 24 0 2
4 0 0 0 0 0 0
5 5 0 5 0 3 0
6 5 0 5 0 3 0
7 5 0 5 0 3 0
8 0 0 0 25 0 3
9 0 0 0 0 0 0