Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – apply multiplication after masking and df.where

I can apply a mask to an entire dataframe and substitute True booleans with a given value, ex, 1.0, like so:

    0   1
 0  0.0 0.0 
 1  3.0 0.0

with:

mask = (df != 0.0)
df = df.where(mask, 1.0)

then:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    0   1
0   0.0 0.0 
1   1.0 0.0

But, instead of a constant float value, how can I substitute each True bool using a multiplication factor, such as, say, the cell value * 0.5, ending up with:

   0   1
0  0.0 0.0 
1  1.5 0.0

>Solution :

You can just do:

df[mask] *= 0.5

Output:

     0    1
0  0.0  0.0
1  1.5  0.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading