how to make pandas row value to zero when row above values are zeros and below value not equal to zero using python pandas

Question:

I have pandas data frame
df = pd.DataFrame({ 'rpm': [2.0, 4.5, 5.6, 6.0, 7.0, 6.0, 0.0, 0.0, 3.0, 5.0, 9.0, 8.9,9.3,0,0,0,6,7,8,9,13] })
here the the above values are zero and below values not equal to zero means the current value has to be zero how to achieve this so far i used this code

for i in range(1, len(df) - 1):
if df['rpm'].iloc[i-1] == 0 and df['rpm'].iloc[i+1] != 0 :
    df['rpm'].iloc[i] = 0

print(df.to_string()) with this code i am not getting expected output
expected output is
df = pd.DataFrame({ 'rpm': [2.0, 4.5, 5.6, 6.0, 7.0, 6.0, 0.0, 0.0, 0.0, 5.0, 9.0, 8.9,9.3,0.0,0.0,0.0,0.0,7,8,9,13] })
if above set of values are zero below set of values are non zero means the value 3 has to be replaced by 0 and in the next set 6 has to replaced by 0 how to do this

Asked By: appu

||

Answers:

You can use shift to check the condition:

df.loc[df['rpm'].shift(1).eq(0) & df['rpm'].shift(-1).ne(0), 'rpm'] = 0
print(df)

# Output:
     rpm
0    2.0
1    4.5
2    5.6
3    6.0
4    7.0
5    6.0
6    0.0
7    0.0
8    0.0  # HERE, old value: 3
9    5.0
10   9.0
11   8.9
12   9.3
13   0.0
14   0.0
15   0.0
16   0.0  # HERE, old value: 6
17   7.0
18   8.0
19   9.0
20  13.0

Details:

m1 = df['rpm'].shift(1).eq(0)
m2 = df['rpm'].shift(-1).ne(0)
out = pd.concat([df['rpm'], m1, m2, m1&m2], keys=['rpm', 'm1', 'm2', 'all'], axis=1)
print(out)

# Output
     rpm    rpm    rpm    rpm
0    2.0  False   True  False
1    4.5  False   True  False
2    5.6  False   True  False
3    6.0  False   True  False
4    7.0  False   True  False
5    6.0  False  False  False
6    0.0  False  False  False
7    0.0   True   True   True  # HERE, already 0
8    3.0   True   True   True  # HERE, set to 0
9    5.0  False   True  False
10   9.0  False   True  False
11   8.9  False   True  False
12   9.3  False  False  False
13   0.0  False  False  False
14   0.0   True  False  False
15   0.0   True   True   True  # HERE, already 0
16   6.0   True   True   True  # HERE, set to 0
17   7.0  False   True  False
18   8.0  False   True  False
19   9.0  False   True  False
20  13.0  False   True  False
Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.