You can use the pandas all method and Boolean logic. As EdChum commented, I am a bit unclear still on your exact example, but a similar example is:

In [1]: df = DataFrame([[1,2],[-3,5]], index=[0,1], columns=['a','b'])
In [2]: df
Out [2]:
   a  b
0  1  2
1 -3  5

In [3]: msk = (df>1) & (df<5)
In [4]: msk
Out [4]:
      a    b
0 False  True
1 False False

In [5]: msk.all(axis=1)
Out [5]:
0  False
1  False
dtype: bool

If you wanted to index the original dataframe by the mask you could do:

In [6]: df[msk]
Out [6]:
     a   b
0  NaN   2
1  NaN NaN

Or as you originally indicated, rows where all the rows are true:

In [7]: idx = msk.all(axis=1)
In [8]: df[idx]
Out [8]:
Empty DataFrame
Columns: [a,b]
Index: []

Or if one row was true

In [9]: idx[0] = True
In [10]: df[idx]
Out [10]:
  a b
0 1 2

For the original question after clarification from the comments, where we want different filtering criteria for different columns:

In [10]: msk1 = df[['a']] < 0
In [11]: msk2 = df[['b']] > 3
In [12]: msk = concat((msk1, msk2), axis=1)
In [12]: slct = msk.all(axis=1)
In [13]: df.ix[slct]
Out [13]:
   a b
1 -3 5
Answer from mgilbert on Stack Overflow
Top answer
1 of 2
18

You can use the pandas all method and Boolean logic. As EdChum commented, I am a bit unclear still on your exact example, but a similar example is:

In [1]: df = DataFrame([[1,2],[-3,5]], index=[0,1], columns=['a','b'])
In [2]: df
Out [2]:
   a  b
0  1  2
1 -3  5

In [3]: msk = (df>1) & (df<5)
In [4]: msk
Out [4]:
      a    b
0 False  True
1 False False

In [5]: msk.all(axis=1)
Out [5]:
0  False
1  False
dtype: bool

If you wanted to index the original dataframe by the mask you could do:

In [6]: df[msk]
Out [6]:
     a   b
0  NaN   2
1  NaN NaN

Or as you originally indicated, rows where all the rows are true:

In [7]: idx = msk.all(axis=1)
In [8]: df[idx]
Out [8]:
Empty DataFrame
Columns: [a,b]
Index: []

Or if one row was true

In [9]: idx[0] = True
In [10]: df[idx]
Out [10]:
  a b
0 1 2

For the original question after clarification from the comments, where we want different filtering criteria for different columns:

In [10]: msk1 = df[['a']] < 0
In [11]: msk2 = df[['b']] > 3
In [12]: msk = concat((msk1, msk2), axis=1)
In [12]: slct = msk.all(axis=1)
In [13]: df.ix[slct]
Out [13]:
   a b
1 -3 5
2 of 2
0
df[df[['DE', 'GA', 'ID']].all(axis=1) * (1 - df[['FL', 'IA']]).all(axis=1)]

The hard part here is understanding why you're using even/odd column positions to determine the treatment. Based on your code, it looks like you want columns 0, 2, and 4 to actually be 1 minus their current values. However, based on what you claim is the expected output, it actually seems like you want colums 1 and 3 to have 1 minus their current values.

My code above reflects the latter assumption. The general idea still works; just tune it to reflect whatever columns you actually need to have 1 minus the value of, assuming you make your desired output more rigorously defined.

Probably that needs to be cleaned up and turned into a proper helper function first that explicitly shows which columns need to have 1 minus their value, versus which columns can be left alone.

🌐
Reddit
reddit.com › r/learnpython › how to do masking operation on multiple columns of a pandas dataframe?
r/learnpython on Reddit: How to do masking operation on multiple columns of a pandas dataframe?
April 13, 2022 -

I am learning about Pandas. I have a df similar to this:

Count orange grey black violet
234 0 33 45 0
453 0 0 23 0

I want to change all of the "color" columns' values so that 0 values are False and values > 0 are True.

I know df[df[column name] == 0] = False or df.loc[df[column name] == 0, column name] = False does what I want for 1 column and that I can use a similar operation on the entire dataframe rather than just one column. But when I try to do it to more than 1 column I get an error. How can I do this kind of masking operation to multiple columns?

This is essentially what I tried:

df[df[['orange', 'grey', 'black']] == 0] = False

This is the error I received:

TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value

Discussions

python - How to use 'mask' in Pandas for multiple columns? - Stack Overflow
For instance, I have 20 columns in dataset, but replace of negative values is required only for two columns. How do I do? For instance, for ArrDelay and DepDelay. Dataset: FlightNum ArrDelay DepDelay More on stackoverflow.com
🌐 stackoverflow.com
python - Pandas dataframe boolean mask on multiple columns - Stack Overflow
I have a dataframe (df) containing several columns with an actual measure and corresponding number of columns (A,B,...) with an uncertainty (dA, dB, ...) for each of these columns: A B dA... More on stackoverflow.com
🌐 stackoverflow.com
python - Multiple Masks on Dataframe - Pandas - Stack Overflow
I have 4 sliders which will multiply an adjusted value at the relevant index using a mask on a series labelled 'code'. I have managed to get the value to adjust with 1 mask but when using multiple ... More on stackoverflow.com
🌐 stackoverflow.com
python - Pandas Mask on multiple Conditions - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.mask.html
pandas.DataFrame.mask — pandas 3.0.6 documentation
The mask method is an application of the if-then idiom. For each element in the caller, if cond is False the element is used; otherwise the corresponding element from other is used.
🌐
Skytowner
skytowner.com › explore › pandas_dataframe_mask_method
Pandas DataFrame | mask method with Examples
Pandas DataFrame.mask(~) replaces all values in the DataFrame that pass a certain criteria with the desired value.
🌐
Brettromero
brettromero.com › pandas-where-and-mask
Pandas: Where and Mask – Brett Romero
April 6, 2021 - That means we would first have to copy the original column, then run this line on the new column. ... The slightly unintuitive aspect of where, at least for me, is that it updates the rows that do not satisfy the condition, i.e. those that evaluate to False. Accordingly, we have to reverse our condition to df['alcohol'] < 10. The mask method is the reverse of where.
🌐
Plus2Net
plus2net.com › python › pandas-dataframe-mask.php
Python Pandas DataFrame mask to get and set value based on condition
my_data['MATH']=my_data['MATH'].mask(my_data['MATH'] > 80,-5) print(my_data) Output · NAME ID MATH ENGLISH 0 Ravi 1 80 81 1 Raju 2 40 70 2 Alex 3 70 40 3 Ron 4 70 50 4 King 5 -5 60 5 Jack 6 30 30 · import pandas as pd my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'], 'ID':[1,2,3,4,5,6], 'MATH':[80,40,73,70,82,30], 'ENGLISH':[81,70,40,50,60,30]} my_data = pd.DataFrame(data=my_dict) my_cond= (my_data['MATH'] >70) & (my_data['MATH'] <75) replace=-7 my_data['MATH'].mask(my_cond,replace,inplace=True) print(my_data) Output
🌐
W3Schools
w3schools.com › python › pandas › ref_df_mask.asp
Pandas DataFrame mask() Method
import pandas as pd data = { "age": [50, 40, 30, 40, 20, 10, 30], "qualified": [True, False, False, False, False, True, True] } df = pd.DataFrame(data) newdf = df.mask(df["age"] > 30) Try it Yourself »
Find elsewhere
🌐
Top Mini Sites
topminisite.com › home › programming › how to use 'mask' in pandas for multiple columns?
How to Use 'Mask' In Pandas For Multiple Columns in 2025?
To use the mask function in pandas for multiple columns, you can create a condition for each column and then combine them using the bitwise '&' (and) operator. This allows you to filter rows based on multiple criteria across different columns.
🌐
YouTube
youtube.com › watch
How to Use Boolean Masks on Multiple Columns in Pandas DataFrames - YouTube
In this video, we’ll explore the powerful technique of using Boolean masks to filter data across multiple columns in Pandas DataFrames. Whether you're cleani...
Published: January 24, 2025
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › mask
Python Pandas DataFrame mask() - Replace Values Based on Condition | Vultr Docs
December 24, 2024 - Using a callable within mask(), this approach allows for dynamic calculation of the replacement values, where entries greater than 2 in the 'data' column are doubled.
🌐
Wrighters
wrighters.io › home › selecting in pandas using where and mask
Selecting in Pandas using where and mask - wrighters.io
April 14, 2021 - But to do this, you end up needing to apply a mask multiple times. >>> sal['total_pay2'] = sal['annual_salary'] >>> mask = sal['salary_or_hourly'] != 'Salary' >>> sal.loc[mask, 'total_pay2'] = sal.loc[mask, 'typical_hours'] * sal.loc[mask, 'hourly_rate'] * 52 · So using where can result in a slightly more simple expression, even if it’s a little long. There are times where you want to create new columns with some sort of complicated condition on a dataframe that might need to be applied across multiple columns.
🌐
Delft Stack
delftstack.com › home › howto › python pandas › pandas mask
How to Mask in Pandas | Delft Stack
February 2, 2024 - As we can see in the code block above, we have successfully filtered data such that we have only values greater than 3 in the value column and the value Beta only in the value2 column. Therefore, with the help of the Masking technique in Pandas, we can efficiently filter data based on our requirement and based on one condition or more than.
Top answer
1 of 2
3

You can use the results of your apply statement to boolean index select from the original dataframe:

results = df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)

Which returns your boolean array above:

       A      B
0  False   True
1   True   True
2   True   True
3   True  False

Now, you can use this array to select rows from your original datafame as follows:

Select where A is True:

df[results.A]

   A    B     dA     dB
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

Select where either A or B are true:

df[results.any(axis=1)]

   A    B     dA     dB
0 -1  3.0  0.310  0.080
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

Select where all the columns true:

df[results.all(axis=1)]

   A    B     dA     dB
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
2 of 2
2

Using the underlying array data, a vectorized approach would be like so -

cols = ['A','B'] # list holding relevant column names
dcols = ['d'+i for i in cols]
out = np.abs(df[cols].values) - 5*df[dcols].values > 0

Sample run -

In [279]: df
Out[279]: 
   A    B     dA     dB
0 -1  3.0  0.310  0.080
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

In [280]: cols = ['A','B'] # list holding relevant column names
     ...: dcols = ['d'+i for i in cols]
     ...: out = np.abs(df[cols].values) - 5*df[dcols].values > 0
     ...: 

In [281]: out
Out[281]: 
array([[False,  True],
       [ True,  True],
       [ True,  True],
       [ True, False]], dtype=bool)

To extract out the valid ones by setting the invalid ones as NaNs, we could use np.where -

In [293]: df[cols] = np.where(out, df[cols], np.nan)

In [294]: df
Out[294]: 
     A    B     dA     dB
0  NaN  3.0  0.310  0.080
1  2.0 -4.0  0.263  0.357
2  5.0  5.0  0.382  0.397
3 -4.0  NaN  0.330  0.115

Also, we could get the rows with all matches with all() reduction along each row -

In [283]: np.flatnonzero(out.all(axis=1))
Out[283]: array([1, 2])
🌐
Programiz
programiz.com › python-programming › pandas › methods › mask
Pandas mask()
import pandas as pd df = pd.DataFrame({ 'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8] }) # replace values in 'A' greater than 2 with their double df['A'] = df['A'].mask(df['A'] > 2, other=lambda x: x * 2) print(df) ... In this example, we have applied the mask() method to the A column of the df DataFrame.
🌐
Stack Overflow
stackoverflow.com › questions › 70816609 › multiple-masks-on-dataframe-pandas
python - Multiple Masks on Dataframe - Pandas - Stack Overflow
I have 4 sliders which will multiply an adjusted value at the relevant index using a mask on a series labelled 'code'. I have managed to get the value to adjust with 1 mask but when using multiple ...
🌐
Saturn Cloud
saturncloud.io › blog › how-to-use-pandas-to-check-multiple-columns-for-a-condition
How to Use Pandas to Check Multiple Columns for a Condition | Saturn Cloud Blog
May 1, 2026 - The apply method is a versatile tool for applying a function to one or more columns in a dataframe. To apply a function to multiple columns, we can use the apply method with the axis parameter set to 1 to apply the function row-wise.