Joe Joe - 3 months ago 17
Python Question

Conditional raplacement with index shift in Pandas

having following column in dataframe:

0
0
0
0
0
5


I would like to check for values greater than a threshold. If found, set to zero and move up by the difference value-threshold, setting threshold on the new position. Let's say threshold=3, then the resulting column has to be:

0
0
0
3
0
0


Any idea for fast transformation?

Answer

For this DataFrame:

df
Out: 
    A
0   0
1   0
2   0
3   0
4   0
5   5
6   0
7   0
8   0
9   0
10  6
11  0
12  0
threshold = 3
above_threshold = df['A'] > threshold
df.loc[df[above_threshold].index - (df.loc[above_threshold, 'A'] - 3).values, 'A'] = 3
df.loc[above_threshold, 'A'] = 0
df
Out: 
    A
0   0
1   0
2   0
3   3
4   0
5   0
6   0
7   3
8   0
9   0
10  0
11  0
12  0
Comments