Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through each row in pandas dataframe and set values equal to nan after a threshold is surpassed?

If I have a pandas dataframe like this:

    0   1   2   3   4   5 
 A  5   5   10  9   4   5
 B  10  10  10  8   1   1
 C  8   8   0   9   6   3
 D  10  10  11  4   2   9
 E  0   9   1   5   8   3

If I set a threshold of 7, how do I loop through each row and set the values after the threshold is no longer met equal to np.nan such that I get a data frame like this:

    0   1   2   3   4   5 
 A  5   5   10  9  NaN NaN
 B  10  10  10  8  NaN NaN
 C  8   8   0   9  NaN NaN
 D  10  10  11  4   2   9
 E  0   9   1   5   8  NaN

Where everything after the last number greater than 7 is set equal to np.nan.

like image 217
Zmann3000 Avatar asked Dec 23 '22 22:12

Zmann3000


1 Answers

Let's try this:

df.where(df.where(df > 7).bfill(axis=1).notna())

Output:

    0   1   2  3    4    5
A   5   5  10  9  NaN  NaN
B  10  10  10  8  NaN  NaN
C   8   8   0  9  NaN  NaN
D  10  10  11  4  2.0  9.0
E   0   9   1  5  8.0  NaN
like image 103
Scott Boston Avatar answered Jan 12 '23 01:01

Scott Boston