Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask all values that occur before the max in a pandas DataFrame

I want to take the result from pd.DataFrame.idxmax and use it to change the values before the index with the maximum value.

If I havedf:

            Mule Creek  Saddle Mtn.  Calvert Creek
Date                                              
2011-05-01   23.400000    35.599998            8.6
2011-05-02   23.400000    35.599998            8.0
2011-05-03   23.400000    35.700001            7.6
2011-05-04   23.400000    50.000000            7.1
2011-05-05   23.100000    35.799999            6.4
2011-05-06   23.000000    35.799999            5.7
2011-05-07   40.000000    35.900002            4.7
2011-05-08   23.100000    36.500000           12.0
2011-05-09   23.299999    37.500000            4.4
2011-05-10   23.200001    37.500000            3.6

and I find where the maximum of each column occurs with:

max = df.idxmax()

I want to make values before the identified maximums max all np.nan

Desired result:

            Mule Creek  Saddle Mtn.  Calvert Creek
Date                                              
2011-05-01         NaN          NaN            NaN
2011-05-02         NaN          NaN            NaN
2011-05-03         NaN          NaN            NaN
2011-05-04         NaN    50.000000            NaN
2011-05-05         NaN    35.799999            NaN
2011-05-06         NaN    35.799999            NaN
2011-05-07   40.000000    35.900002            NaN
2011-05-08   23.100000    36.500000           12.0
2011-05-09   23.299999    37.500000            4.4
2011-05-10   23.200001    37.500000            3.6
like image 848
dubbbdan Avatar asked Jan 28 '26 15:01

dubbbdan


1 Answers

Can check where the cumulative max is the same as the max:

df.where(df.cummax() == df.max())

            Mule Creek  Saddle Mtn.  Calvert Creek
Date                                              
2011-05-01         NaN          NaN            NaN
2011-05-02         NaN          NaN            NaN
2011-05-03         NaN          NaN            NaN
2011-05-04         NaN    50.000000            NaN
2011-05-05         NaN    35.799999            NaN
2011-05-06         NaN    35.799999            NaN
2011-05-07   40.000000    35.900002            NaN
2011-05-08   23.100000    36.500000           12.0
2011-05-09   23.299999    37.500000            4.4
2011-05-10   23.200001    37.500000            3.6
like image 171
ALollz Avatar answered Jan 30 '26 06:01

ALollz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!