链条3条件|对于按位OR,对于高于和低于1的行,使用带有
shift的掩码:
mask1 = df['Grad'] == 1
mask2 = df['Grad'].shift() == 1
mask3 = df['Grad'].shift(-1) == 1
mask1 = df['Grad'] != 0
mask2 = df['Grad'].shift() != 0
mask3 = df['Grad'].shift(-1) != 0
mask = mask1 | mask2 | mask3
df.loc[mask, ['Vorgabe', 'Temp']] = np.nan
print (df)
OptOpTemp OpTemp BSP Grad Vorgabe Temp
0 22.0 20.0 5 0.0 22.0 20.0
1 22.0 20.5 7 0.0 NaN NaN
2 22.0 21.0 8 1.0 NaN NaN
3 22.0 21.0 6 0.0 NaN NaN
4 22.0 23.5 7 0.0 22.0 20.0
5 23.0 21.5 1 0.0 NaN NaN
6 24.0 22.5 3 1.0 NaN NaN
7 24.0 23.0 4 0.0 NaN NaN
8 24.0 25.5 9 0.0 24.0 25.5
多行的一般解决方案:
N = 1
#create range for test value betwen -N to N
r = np.concatenate([np.arange(0, N+1), np.arange(-1, -N-1, -1)])
#create boolean mask by comparing with shift and join together by reduce
mask = np.logical_or.reduce([df['Grad'].shift(x) == 1 for x in r])
df.loc[mask, ['Vorgabe', 'Temp']] = np.nan
编辑:
您可以将两个面具连接在一起:
N = 1
r1 = np.concatenate([np.arange(0, N+1), np.arange(-1, -N-1, -1)])
mask1 = np.logical_or.reduce([df['Grad'].shift(x) == 1 for x in r1])
N = 2
r2 = np.concatenate([np.arange(0, N+1), np.arange(-1, -N-1, -1)])
mask2 = np.logical_or.reduce([df['Grad'].shift(x) == 1.5 for x in r2])
#if not working ==1.5 because precision of floats
#mask2 = np.logical_or.reduce([np.isclose(df['Grad'].shift(x), 1.5) for x in r2])
mask = mask1 | mask2
df.loc[mask, ['Vorgabe', 'Temp']] = np.nan
print (df)
OptOpTemp OpTemp BSP Grad Vorgabe Temp
0 22.0 20.0 5 0.0 22.0 20.0
1 22.0 20.5 7 0.0 NaN NaN
2 22.0 21.0 8 1.0 NaN NaN
3 22.0 21.0 6 0.0 NaN NaN
4 22.0 23.5 7 0.0 NaN NaN
5 23.0 21.5 1 0.0 NaN NaN
6 24.0 22.5 3 1.5 NaN NaN
7 24.0 23.0 4 0.0 NaN NaN
8 24.0 25.5 9 0.0 NaN NaN