Search code examples
pythonpandasmasking

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:

    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