As noted in the comments, situations where you would need to get a "mask" like that seem rare (and chances are, you not in one of them). Consequently, there is probably no nice "built-in" solution for them in Pandas.

None the less, you can achieve what you need, using a hack like the following, for example:

mask = (df == df) & (df.columns == 'col_1')

Update:. As noted in the comments, if your data frame contains nulls, the mask computed this way will always be False at the corresponding locations. If this is a problem, the safer option is:

mask = ((df == df) | df.isnull()) & (df.columns == 'col_1')
Answer from KT. on Stack Overflow
🌐
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.
🌐
W3Schools
w3schools.com › python › pandas › ref_df_mask.asp
Pandas DataFrame mask() Method
import pandas as pd data = { "age": ... = df.mask(df["age"] > 30) Try it Yourself » · The mask() method replaces the values of the rows where the condition evaluates to True....
Top answer
1 of 2
7

As noted in the comments, situations where you would need to get a "mask" like that seem rare (and chances are, you not in one of them). Consequently, there is probably no nice "built-in" solution for them in Pandas.

None the less, you can achieve what you need, using a hack like the following, for example:

mask = (df == df) & (df.columns == 'col_1')

Update:. As noted in the comments, if your data frame contains nulls, the mask computed this way will always be False at the corresponding locations. If this is a problem, the safer option is:

mask = ((df == df) | df.isnull()) & (df.columns == 'col_1')
2 of 2
0

You could transpose your dataframe than compare it with the columns and then transpose back. A bit weird but working example:

import pandas as pd
from io import StringIO

data = """
col1,col2
1,3
2,1
3,8
"""

df = pd.read_csv(StringIO(data))
mask = (df.T == df['col1']).T

In [176]: df
Out[176]:
   col1  col2
0     1     3
1     2     1
2     3     8


In [178]: mask
Out[178]:
   col1   col2
0  True  False
1  True  False
2  True  False

EDIT

I found another answer for that, you could use isin method:

In [41]: df.isin(df.col1)
Out[41]:
   col1   col2
0  True  False
1  True  False
2  True  False

EDIT2

As @DSM show in the comment that these two cases not working correctly. So you should use @KT. method. But.. Let's play more with transpose:

df.col2 = df.col1

In [149]: df
Out[149]:
   col1  col2
0     1     1
1     2     2
2     3     3

In [147]: df.isin(df.T[df.columns == 'col1'].T)
Out[147]:
   col1   col2
0  True  False
1  True  False
2  True  False
🌐
Programiz
programiz.com › python-programming › pandas › methods › mask
Pandas mask()
The mask() method in Pandas is used to replace values where certain conditions are met. import pandas as pd # create a DataFrame df = pd.DataFrame({ 'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8] }) # replace values in column 'A' that are greater than 2 with -1 df['A'] = df['A'].mask(df['A'] > 2, -1) ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-pandas-dataframe-mask
Python | Pandas dataframe.mask() | GeeksforGeeks
November 19, 2018 - Pandas is one of those packages ... dataframe.mask() function return an object of same shape as self and whose corresponding entries are from self where cond is False and otherwise are from other object....
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.5 › reference › api › pandas.DataFrame.mask.html
pandas.DataFrame.mask — pandas 1.5.3 documentation
>>> s.where(s > 1, 10) 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> s.mask(s > 1, 10) 0 0 1 1 2 10 3 10 4 10 dtype: int64 · >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 >>> m = df % 3 == 0 >>> df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 >>> df.where(m, -df) == np.where(m, df, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True >>> df.where(m, -df) == df.mask(~m, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True
🌐
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.
🌐
Plus2Net
plus2net.com › python › pandas-dataframe-mask.php
Python Pandas DataFrame mask to get and set value based on condition
Difference between MASK & WHERE MASK: Data is updated as NaN (if other is not given ) if cond ( condition ) is True. WHERE : Data is updated as NaN (if other is not given ) if cond ( condition ) is False. DataFrame.where() Update where MATH column is more than 80 · import pandas as pd my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'], 'ID':[1,2,3,4,5,6], 'MATH':[80,40,70,70,82,30], 'ENGLISH':[81,70,40,50,60,30]} my_data = pd.DataFrame(data=my_dict) my_data=my_data.mask(my_data['MATH'] > 80,-5) print(my_data) Output ·
🌐
Wrighters
wrighters.io › home › selecting in pandas using where and mask
Selecting in Pandas using where and mask - wrighters.io
April 14, 2021 - >>> 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.
Find elsewhere
Top answer
1 of 2
1

Could be due to incompatible dtypes. Define a function to encapsulate the functionality, then run it for different dtype-columned dataframes, see below example:

import numpy as np
import pandas as pd


def mask_column(df):
    print(df)
    col_to_mask = df.columns.values[1]
    lower = np.percentile(df[col_to_mask], 25)
    upper = np.percentile(df[col_to_mask], 75)
    outliers = [x for x in df[col_to_mask] if x < lower or x > upper]
    print('Identified Outliers %d' % len(outliers))
    mask = ((df[col_to_mask] < lower) | (df[col_to_mask] > upper))
    df[col_to_mask][mask] = np.nan
    print(df)


df_1 = pd.DataFrame(np.random.randint(0, 1000, size=(4, 10)),
                  columns=('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J')
                  )

df_2 = pd.DataFrame(np.random.randint(0, 1000, size=(4, 10)),
                  columns=('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J')
                  )
df_2['B'] = df_1['B'].astype(float)

df_3 = pd.DataFrame(np.random.randint(0, 1000, size=(4, 10)),
                  columns=('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J')
                  )
df_3['B'] = df_1['B'].astype(str)

# mask_column(df_1)
# mask_column(df_2)
mask_column(df_3)

The first two function calls will succeed in applying the boolean mask, but not the third function call:

Traceback (most recent call last):
  File "C:/Users/gtrm/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_56.py", line 34, in <module>
    mask_column(df_3)
  File "C:/Users/gtrm/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_56.py", line 9, in mask_column
    lower = np.percentile(df[col_to_mask], 25)
  File "<__array_function__ internals>", line 5, in percentile
  File "C:\Users\gtrm\AppData\Local\Continuum\anaconda3\envs\py38\lib\site-packages\numpy\lib\function_base.py", line 3705, in percentile
    return _quantile_unchecked(
  File "C:\Users\gtrm\AppData\Local\Continuum\anaconda3\envs\py38\lib\site-packages\numpy\lib\function_base.py", line 3824, in _quantile_unchecked
    r, k = _ureduce(a, func=_quantile_ureduce_func, q=q, axis=axis, out=out,
  File "C:\Users\gtrm\AppData\Local\Continuum\anaconda3\envs\py38\lib\site-packages\numpy\lib\function_base.py", line 3403, in _ureduce
    r = func(a, **kwargs)
  File "C:\Users\gtrm\AppData\Local\Continuum\anaconda3\envs\py38\lib\site-packages\numpy\lib\function_base.py", line 3941, in _quantile_ureduce_func
    x1 = take(ap, indices_below, axis=axis) * weights_below
TypeError: can't multiply sequence by non-int of type 'float'
     A    B    C    D    E    F    G    H    I    J
0  450  524  545  697   94  703   97  894  710  974
1  238  367   48  224  698  116  974  943  235  244
2  503  107  937  700  506  411  818  511  932  641
3  993  148  284  580  218  957  917   73   96  853
2 of 2
1
  • I recommend using pandas.DataFrame.quantile.
    • With the default of axis=0, the specified quantile for each column is calculated.
    • By default, numeric_only=True, so only numeric values are considered, but if False is specified, this will work for datetime and timedelta data as well.
    • Columns that are not of numeric / dateime / timedelta type, will be ignored.
  • Use Pandas: Boolean Indexing to filter the dataframe along all the columns, at once.
  • To get the number of remaining numeric values, use filtered.count()
    • To find the number of NaN values, use df.count() - filtereed.count().
    • See pandas.DataFrame.count for parameter specifics.
  • In regards to the "real" dataframe, it's not possible to determine the issue, as it is not available.
    • Use df.info() to verify the Dtype of columns are a numeric type.
import pandas as pd
import numpy as np

# test data and dataframe
np.random.seed(50)
df = pd.DataFrame(np.random.randint(0, 10000, size=(4,10)) / 10, columns=('A','B','C','D','E','F','G','H','I','J'))
df['k'] = ['a', 'b', 'c', 'd']

# display(df)

       A      B      C      D      E      F      G      H      I      J  k
0  560.0  625.3  832.4  621.4  826.2  791.7  730.1  623.9  741.8  211.9  a
1  855.9  147.6  302.2   60.3  220.2  431.4  730.2  347.6  388.3  648.5  b
2  511.8   50.7  461.4  371.4  451.0  727.3  963.5  561.9   37.1  800.2  c
3   99.2  493.1  180.2  612.8  574.2  572.6  102.4  195.0  988.2  824.3  d


# calculate upper and lower quantiles
quantiles = df.quantile([.25, .75])

# display(quantiles)
            A        B       C        D      E      F        G       H      I        J
0.25  408.650  123.375  271.70  293.625  393.3  537.3  573.175  309.45  300.5  539.350
0.75  633.975  526.150  554.15  614.950  637.2  743.4  788.525  577.40  803.4  806.225

# filter the dataframe
filtered = df[(df < quantiles.loc[0.75]) & (df > quantiles.loc[0.25])]

# display(filtered)
       A      B      C      D      E      F      G      H      I      J    k
0  560.0    NaN    NaN    NaN    NaN    NaN  730.1    NaN  741.8    NaN  NaN
1    NaN  147.6  302.2    NaN    NaN    NaN  730.2  347.6  388.3  648.5  NaN
2  511.8    NaN  461.4  371.4  451.0  727.3    NaN  561.9    NaN  800.2  NaN
3    NaN  493.1    NaN  612.8  574.2  572.6    NaN    NaN    NaN    NaN  NaN

print(filtered.count())
[out]:
A    2
B    2
C    2
D    2
E    2
F    2
G    2
H    2
I    2
J    2
k    0
dtype: int64
🌐
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.
🌐
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.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas dataframe mask() method
Pandas DataFrame mask() Method - Spark By {Examples}
December 11, 2024 - In pandas, the mask() method is used to replace values in a DataFrame or Series where a specified condition is True. It essentially allows you to mask or
🌐
Rip Tutorial
riptutorial.com › masking data based on column value
pandas Tutorial => Masking data based on column value
Accessing a single column from a data frame, we can use a simple comparison == to compare every element in the column to the given variable, producing a pd.Series of True and False · df['size'] == 'small' 0 False 1 True 2 True 3 True Name: size, dtype: bool · This pd.Series is an extension of an np.array which is an extension of a simple list, Thus we can hand this to the __getitem__ or [] accessor as in the above example. size_small_mask = df['size'] == 'small' df[size_small_mask] color name size 1 blue violet small 2 red tulip small 3 blue harebell small
🌐
TopDealsNet
topminisite.com › blog › how-to-use-mask-in-pandas-for-multiple-columns
How to Use 'Mask' In Pandas For Multiple Columns in 2026?
September 21, 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.
🌐
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.
🌐
Educative
educative.io › answers › what-is-the-pandas-mask-method-in-python
What is the pandas mask() method in Python?
The mask() method can also take ... odd numbers). The mask() method in pandas replaces specific elements in a DataFrame or series with another value based on a condition....
🌐
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

🌐
Medium
medium.com › @heyamit10 › understanding-the-mask-method-in-pandas-48b55840e679
Understanding the mask() Method in Pandas | by Hey Amit | Medium
March 6, 2025 - And that’s exactly what the mask() method in Pandas does—it helps you "cover up" certain data based on conditions you define.
🌐
w3resource
w3resource.com › pandas › dataframe › dataframe-mask.php
Pandas DataFrame: mask() function - w3resource
August 19, 2022 - DataFrame.mask(self, cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False) ... Download the Pandas DataFrame Notebooks from here.