Possible to use `mask` or `where` in pandas on a whole dataframe but change only one columns

Viewed 2222

When method chaining with pandas dataframes, it's often necessary to mask one particular column, not a whole dataframe.

The documentation for pandas has mask or where for a whole dataframe or a series.

Is there some way to pass mask to a whole dataframe, but only change one column?

As an example, say we have data:

import pandas as pd

df = pd.DataFrame({'A' : [0,1,2], 'B' : [3,4,5]})

Now we can either do df.mask(df > 0, 2) and the whole dataframe will be:

|A | B | 
|--|---|
|0 | 2 |
|2 | 2 |
|2 | 2 |

Or I can do df.A.mask(df.A >0,2) which will give me:

|A|
|0|
|2|
|2|

Is there a way to do this?:

df.mask(df.A > 0, 2) 

|A | B|
|0 | 3|
|2 | 4|
|2 | 5|
2 Answers

You can replace a specified column by using ``ìnplace=True``` in function. Same as for where.

df.A.mask(df.A>0, 2, inplace=True)

You can use pandas assign together with mask.

df.mask(df['A']>0, df.assign(**{'A': 2}))
Related