🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.where.html
pandas.DataFrame.where — pandas 3.0.5 documentation
Where the condition evaluates to True, the original values are retained; where it evaluates to False, values are replaced with corresponding entries from other. ... Where cond is True, keep the original value. Where False, replace with corresponding value from other.
🌐
IONOS
ionos.com › digital guide › websites › web development › python pandas: dataframe where
How to apply conditions in pandas DataFrames with where()
June 26, 2025 - When applied to a DataFrame, only ... condition (cond) will remain as they are. Any other values will be replaced with what you specify in the other parameter. Pandas DataFrame.where() accepts different pa­ra­me­ters that fa­cil­i­tate flexible data man­age­ment and mod­i­fi­ca­tion: The where() function can be useful in various scenarios that require con­di­tion­al data ma­nip­u­la­tion. This could include data cleaning or creating new columns based on ...
Discussions

python - Selecting specific columns in where condition using Pandas - Stack Overflow
I have a below Dataframe with 3 columns: df = DataFrame(query, columns=["Processid", "Processdate", "ISofficial"]) In Below code, I get Processdate based on Processid... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I select rows from a DataFrame based on column values? - Stack Overflow
The accepted answer shows how to filter rows in a pandas DataFrame based on column values using .loc. Use == to select rows where the column equals a value. Use .isin() to select rows where the column value is in a list. Combine multiple conditions using & (with parentheses). More on stackoverflow.com
🌐 stackoverflow.com
how to select rows based on some conditions [pandas]
yeah don't iterate over the rows, just filter the dataframe using a conditional. examples: df = df[df['score'] >= 90.0] df = df[df['username'].isin(AUTHORIZED_USERS)] df = df[df['name'].str.contains('good')] More on reddit.com
🌐 r/learnpython
5
2
October 29, 2021
How to drop duplicates only on rows where a column has a certain value and leave out the rest?
Not familiar with data frames, but try something like this seen = set() deduped = [] for row in data: if row['code'] == 5: deduped.append(row) else: key = row['user'] + row['host'] if key not in seen: seen.add(key) deduped.append(row) More on reddit.com
🌐 r/learnpython
3
1
December 15, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-dataframe-where
Pandas DataFrame.where()-Python - GeeksforGeeks
June 24, 2025 - DataFrame.where() function replace values in a DataFrame based on a condition. It allows you to keep the original value where a condition is True and replace it with something else e.g., NaN or a custom value where the condition is False.
🌐
Pandas
pandas.pydata.org › docs › getting_started › intro_tutorials › 03_subset_data.html
How do I select a subset of a DataFrame? — pandas 3.0.5 documentation
The condition inside the selection brackets titanic["Age"] > 35 checks for which rows the Age column has a value larger than 35: In [14]: titanic["Age"] > 35 Out[14]: 0 False 1 True 2 False 3 False 4 False ... 886 False 887 False 888 False 889 False 890 False Name: Age, Length: 891, dtype: bool · The output of the conditional expression (>, but also ==, !=, <, <=,… would work) is actually a pandas Series of boolean values (either True or False) with the same number of rows as the original DataFrame.
🌐
Dataquest
dataquest.io › home › blog › tutorial: add a column to a pandas dataframe based on an if-else condition
Add a Column in a Pandas DataFrame Based on an If-Else Condition
March 6, 2023 - While this is a very superficial analysis, we’ve accomplished our true goal here: adding columns to pandas DataFrames based on conditional statements about values in our existing columns.
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › where
Python Pandas DataFrame where() - Filter Data Conditionally | Vultr Docs
December 26, 2024 - The where() function in Pandas provides a powerful way to filter and manipulate data frames based on conditional logic, maintaining the integrity and structure of the original data.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas.dataframe.where() examples
pandas.DataFrame.where() Examples - Spark By {Examples}
October 8, 2024 - pandas.DataFrame.where() function is similar to if-then/if else that is used to check the one or multiple conditions of an expression in DataFrame and
Find elsewhere
🌐
Statology
statology.org › home › pandas: how to select columns based on condition
Pandas: How to Select Columns Based on Condition
November 4, 2022 - Method 3: Select Columns Where At Least One Row Meets Multiple Conditions · #select columns where at least one row has a value between 10 and 15 df.loc[:, ((df>=10) & (df<=15)).any()] The following examples show how to use each method with the following pandas DataFrame:
🌐
Towards Data Science
towardsdatascience.com › home › latest › 3 methods to create conditional columns with python pandas and numpy
3 Methods to Create Conditional Columns with Python Pandas and Numpy | Towards Data Science
January 21, 2025 - Pandas where function only allows for updating the values that do not meet the given condition. However, the where function of Numpy allows for updating values that meet and do not meet the given condition.
🌐
GeeksforGeeks
geeksforgeeks.org › selecting-rows-in-pandas-dataframe-based-on-conditions
Selecting rows in pandas DataFrame based on conditions - GeeksforGeeks
August 7, 2024 - Let’s see how to Select rows based on some conditions in Pandas DataFrame. Selecting rows based on particular column value using '>', '=', '=', '<=', '!=' operator. Code #1 : Selecting all the rows from the given dataframe in which 'Percentage' is greater than 80 using basic method.
🌐
Data to Fish
datatofish.com › if-condition-in-pandas-dataframe
Two Ways to Apply an If-Condition on a pandas DataFrame
In this tutorial, you will learn two ways to apply an if condition a DataFrame. ... df.loc[df['column'] == condition_value, 'target_column' ] = then_value df['target_column'] = df['column'].apply(lambda x: then_value if x == condition_value)
🌐
Towards Data Science
towardsdatascience.com › home › latest › 5 ways to apply if-else conditional statements in pandas
5 Ways to Apply If-Else Conditional Statements in Pandas | Towards Data Science
January 28, 2025 - The numpy.where() function is an elegant and efficient python function that you can use to add a new column based on 'true' or 'false' binary conditions.
🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
pandas: Select rows by multiple conditions | note.nkmk.me
August 8, 2023 - pandas: Split string columns by delimiters or regular expressions · List vs. Array vs. numpy.ndarray in Python · pandas: How to use astype() to cast dtype of DataFrame · pandas: Count values in DataFrame/Series with conditions · pandas: Replace values based on conditions with where(), mask() pandas: Remove NaN (missing values) with dropna() pandas: Interpolate NaN (missing values) with interpolate() pandas: Shuffle rows/elements of DataFrame/Series ·
Top answer
1 of 16
6655

To select rows whose column value equals a scalar, some_value, use ==:

df.loc[df['column_name'] == some_value]

To select rows whose column value is in an iterable, some_values, use isin:

df.loc[df['column_name'].isin(some_values)]

Combine multiple conditions with &:

df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]

Note the parentheses. Due to Python's operator precedence rules, & binds more tightly than <= and >=. Thus, the parentheses in the last example are necessary. Without the parentheses

df['column_name'] >= A & df['column_name'] <= B

is parsed as

df['column_name'] >= (A & df['column_name']) <= B

which results in a Truth value of a Series is ambiguous error.


To select rows whose column value does not equal some_value, use !=:

df.loc[df['column_name'] != some_value]

The isin returns a boolean Series, so to select rows whose value is not in some_values, negate the boolean Series using ~:

df = df.loc[~df['column_name'].isin(some_values)] # .loc is not in-place replacement

For example,

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

yields

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

If you have multiple values you want to include, put them in a list (or more generally, any iterable) and use isin:

print(df.loc[df['B'].isin(['one','three'])])

yields

     A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
3  bar  three  3   6
6  foo    one  6  12
7  foo  three  7  14

Note, however, that if you wish to do this many times, it is more efficient to make an index first, and then use df.loc:

df = df.set_index(['B'])
print(df.loc['one'])

yields

       A  C   D
B              
one  foo  0   0
one  bar  1   2
one  foo  6  12

or, to include multiple values from the index use df.index.isin:

df.loc[df.index.isin(['one','two'])]

yields

       A  C   D
B              
one  foo  0   0
one  bar  1   2
two  foo  2   4
two  foo  4   8
two  bar  5  10
one  foo  6  12
2 of 16
854

There are several ways to select rows from a Pandas dataframe:

  1. Boolean indexing (df[df['col'] == value] )
  2. Positional indexing (df.iloc[...])
  3. Label indexing (df.xs(...))
  4. df.query(...) API

Below I show you examples of each, with advice when to use certain techniques. Assume our criterion is column 'A' == 'foo'

(Note on performance: For each base type, we can keep things simple by using the Pandas API or we can venture outside the API, usually into NumPy, and speed things up.)


Setup

The first thing we'll need is to identify a condition that will act as our criterion for selecting rows. We'll start with the OP's case column_name == some_value, and include some other common use cases.

Borrowing from @unutbu:

import pandas as pd, numpy as np

df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})

1. Boolean indexing

... Boolean indexing requires finding the true value of each row's 'A' column being equal to 'foo', then using those truth values to identify which rows to keep. Typically, we'd name this series, an array of truth values, mask. We'll do so here as well.

mask = df['A'] == 'foo'

We can then use this mask to slice or index the data frame

df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

This is one of the simplest ways to accomplish this task and if performance or intuitiveness isn't an issue, this should be your chosen method. However, if performance is a concern, then you might want to consider an alternative way of creating the mask.


2. Positional indexing

Positional indexing (df.iloc[...]) has its use cases, but this isn't one of them. In order to identify where to slice, we first need to perform the same boolean analysis we did above. This leaves us performing one extra step to accomplish the same task.

mask = df['A'] == 'foo'
pos = np.flatnonzero(mask)
df.iloc[pos]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

3. Label indexing

Label indexing can be very handy, but in this case, we are again doing more work for no benefit

df.set_index('A', append=True, drop=False).xs('foo', level=1)

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

4. df.query() API

pd.DataFrame.query is a very elegant/intuitive way to perform this task, but is often slower. However, if you pay attention to the timings below, for large data, the query is very efficient. More so than the standard approach and of similar magnitude as my best suggestion.

df.query('A == "foo"')

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

My preference is to use the Boolean mask

Actual improvements can be made by modifying how we create our Boolean mask.

mask alternative 1 Use the underlying NumPy array and forgo the overhead of creating another pd.Series

mask = df['A'].values == 'foo'

I'll show more complete time tests at the end, but just take a look at the performance gains we get using the sample data frame. First, we look at the difference in creating the mask

%timeit mask = df['A'].values == 'foo'
%timeit mask = df['A'] == 'foo'

5.84 µs ± 195 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
166 µs ± 4.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Evaluating the mask with the NumPy array is ~ 30 times faster. This is partly due to NumPy evaluation often being faster. It is also partly due to the lack of overhead necessary to build an index and a corresponding pd.Series object.

Next, we'll look at the timing for slicing with one mask versus the other.

mask = df['A'].values == 'foo'
%timeit df[mask]
mask = df['A'] == 'foo'
%timeit df[mask]

219 µs ± 12.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
239 µs ± 7.03 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

The performance gains aren't as pronounced. We'll see if this holds up over more robust testing.


mask alternative 2 We could have reconstructed the data frame as well. There is a big caveat when reconstructing a dataframe—you must take care of the dtypes when doing so!

Instead of df[mask] we will do this

pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

If the data frame is of mixed type, which our example is, then when we get df.values the resulting array is of dtype object and consequently, all columns of the new data frame will be of dtype object. Thus requiring the astype(df.dtypes) and killing any potential performance gains.

%timeit df[m]
%timeit pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

216 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.43 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

However, if the data frame is not of mixed type, this is a very useful way to do it.

Given

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

d1

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5

%%timeit
mask = d1['A'].values == 7
d1[mask]

179 µs ± 8.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Versus

%%timeit
mask = d1['A'].values == 7
pd.DataFrame(d1.values[mask], d1.index[mask], d1.columns)

87 µs ± 5.12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

We cut the time in half.


mask alternative 3

@unutbu also shows us how to use pd.Series.isin to account for each element of df['A'] being in a set of values. This evaluates to the same thing if our set of values is a set of one value, namely 'foo'. But it also generalizes to include larger sets of values if needed. Turns out, this is still pretty fast even though it is a more general solution. The only real loss is in intuitiveness for those not familiar with the concept.

mask = df['A'].isin(['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

However, as before, we can utilize NumPy to improve performance while sacrificing virtually nothing. We'll use np.in1d

mask = np.in1d(df['A'].values, ['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing

I'll include other concepts mentioned in other posts as well for reference.

Code Below

Each column in this table represents a different length data frame over which we test each function. Each column shows relative time taken, with the fastest function given a base index of 1.0.

res.div(res.min())

                         10        30        100       300       1000      3000      10000     30000
mask_standard         2.156872  1.850663  2.034149  2.166312  2.164541  3.090372  2.981326  3.131151
mask_standard_loc     1.879035  1.782366  1.988823  2.338112  2.361391  3.036131  2.998112  2.990103
mask_with_values      1.010166  1.000000  1.005113  1.026363  1.028698  1.293741  1.007824  1.016919
mask_with_values_loc  1.196843  1.300228  1.000000  1.000000  1.038989  1.219233  1.037020  1.000000
query                 4.997304  4.765554  5.934096  4.500559  2.997924  2.397013  1.680447  1.398190
xs_label              4.124597  4.272363  5.596152  4.295331  4.676591  5.710680  6.032809  8.950255
mask_with_isin        1.674055  1.679935  1.847972  1.724183  1.345111  1.405231  1.253554  1.264760
mask_with_in1d        1.000000  1.083807  
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-creating-a-pandas-dataframe-column-based-on-a-given-condition
Python | Creating a Pandas dataframe column based on a given condition - GeeksforGeeks
October 30, 2025 - Given a DataFrame containing details of a cultural event, add a column called Price which contains the ticket price for each day based on the type of event. ... import pandas as pd df = pd.DataFrame({'Date': ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event': ['Music', 'Poetry', 'Music', 'Comedy', 'Poetry']}) print(df)
🌐
Statology
statology.org › home › pandas: how to use equivalent of np.where()
Pandas: How to Use Equivalent of np.where()
June 24, 2022 - df['col'] = (value_if_false).where(condition, value_if_true) The following example shows how to use the pandas where() function in practice. ... import pandas as pd #create DataFrame df = pd.DataFrame({'A': [18, 22, 19, 14, 14, 11, 20, 28], 'B': [5, 7, 7, 9, 12, 9, 9, 4]}) #view DataFrame print(df) A B 0 18 5 1 22 7 2 19 7 3 14 9 4 14 12 5 11 9 6 20 9 7 28 4 · We can use the following pandas where() function to update the values in column A based on a specific condition:
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas create conditional column in dataframe
Pandas Create Conditional Column in DataFrame - Spark By {Examples}
March 27, 2024 - You can create a conditional column in pandas DataFrame by using np.where(), np.select(), DataFrame.map(), DataFrame.assign(), DataFrame.apply(),
🌐
Educative
educative.io › answers › what-is-pandas-dataframewhere-in-python
What is Pandas DataFrame.where() in Python?
Line 10: We invoke the DataFrame() method from the Pandas package to convert this nested list into a DataFrame of Name, Class, and Marks. Line 12: We create a Boolean series of students with the name Butller. Lines 14–16: We call the df.where() function to filter the student Buttler's data. Here, the code is the same as above other than the filtering condition. Instead of one, we can also use multiple conditions using logical operators.