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
Answer from unutbu on Stack Overflow
🌐
Statology
statology.org › home › pandas: how to select rows based on column values
Pandas: How to Select Rows Based on Column Values
March 25, 2025 - You’re right that this is a common need when working with pandas. To select rows where a string column equals one of multiple values (like team “B” OR “C”), the `.isin()` method actually works perfectly.
🌐
Medium
medium.com › @whyamit404 › pandas-where-column-equals-26503e95969a
Pandas Where Column Equals
April 21, 2025 - Another mistake is neglecting to group conditions properly with parentheses. Remember, clarity is key! What does pandas where column equals mean? This term refers to filtering DataFrame rows based on specific column values.
Discussions

python - pandas dataframe: how to select rows where one column-value is like 'values in a list' - Stack Overflow
3 Selecting Rows in Dataframe that have any column equal to any item in a list · 1 Select DataFrame column elements that are in a list · 3 Select rows from a DataFrame based on list values in a column in pandas More on stackoverflow.com
🌐 stackoverflow.com
how to update a pandas dataframe column value, when a specific string appears in another column?
It's not something you'd really use .apply for. You would use boolean indexing, e.g. df['A'].str.contains('foo') would give you a Series of True/False values. You can then use .loc to set column(s) to a particular value for the True rows: df.loc[df['A'].str.contains('foo'), 'B'] = 'bar' More on reddit.com
🌐 r/learnpython
7
3
July 24, 2024
[Pandas] If cell = x, get value from another column. Otherwise, get value from previous row in that column.
I tried the following code but I am getting "A value is trying to be set on a copy of a slice from a dataframe" Did you follow the link in the traceback? The explanation is there. What I want to do is create a new column where if Level = 0 then that new column equals the value of the "item" in that row. Otherwise it equals the value in the previous row. Regarding the solution, always avoid looping over a DataFrame, it should be the last option as it's very slow. In your case, you can use numpy.where since you have a binary choice, and to get the previous rows you can use the shift method df['New Column'] = np.where(df['Level'] == 0, df['Item'], df['Item'].shift()) More on reddit.com
🌐 r/learnpython
9
19
August 5, 2021
I am looking for a partial string in each row of my pandas Dataframe, I created a Dataframe where the rows are not all equal, so I cannot select by column
If I am understanding you are looking for the string in each row that ends with "OBR" and then want the value in the cell 3 to the left of it? More on reddit.com
🌐 r/learnpython
17
4
January 21, 2022
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  
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to select rows from pandas dataframe based on column values
How To Select Rows From Pandas DataFrame Based on Column Values | Towards Data Science
January 20, 2025 - We can even omit loc and provide the boolean condition when indexing the pandas DataFrame as shown below: ... Note that instead of df['B'] you can also reference column B using df.B. For example the statement below is equivalent to the one above. ... In the context of Python, it is a common practise to name such boolean conditions as mask that we then pass to DataFrame when indexing it. ... Having introduced a few possible ways you can use to select rows based on column value equality to a scalar, we should highlight that loc[] is the way to go.
🌐
Medium
medium.com › @akaivdo › pandas-select-rows-from-a-dataframe-based-on-column-values-29aef08388ec
Pandas >> Select Rows From a DataFrame Based on Column Values | by NextGenTechDawn | Medium
May 6, 2023 - To select rows from a Pandas DataFrame based on column values, you can use boolean indexing. Here’s an example: import pandas as pd # Create a sample DataFrame df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie', 'Dave', 'Eva'], 'Age': ...
🌐
RS Blog
reneshbedre.com › blog › pandas-select-rows-value-matching.html
Query pandas DataFrame to select rows based on value and condition matching
August 24, 2021 - Select rows based on the exact match with the multiple column values, # select the rows where col1 value is equal to 2 and col3 is equal to Y # using & bitwise operator df[(df['col1']==2) & (df['col3']=='Y') ] # output col1 col2 col3 1 2.0 city Y # select the rows where col1 value is equal ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas select rows based on column values
Pandas Select Rows Based on Column Values - Spark By {Examples}
June 12, 2025 - In pandas, you can select rows based on column values using boolean indexing or using methods like DataFrame.loc[] attribute, DataFrame.query(), or
Find elsewhere
🌐
Medium
medium.com › @iambeniwal12 › how-to-select-rows-from-a-dataframe-based-on-column-values-in-pandas-83b091bade91
How to Select Rows from a DataFrame Based on Column Values in Pandas | by Narender Beniwal | Medium
November 1, 2024 - Let’s explore how to achieve this in Python with Pandas. To select rows based on a specific column value, you can use the df.loc[] method combined with a condition.
🌐
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.6 documentation
Fare Cabin Embarked 0 1 0 3 ... 7.2500 NaN S 1 2 1 1 ... 71.2833 C85 C 2 3 1 3 ... 7.9250 NaN S 3 4 1 1 ... 53.1000 C123 S 4 5 0 3 ... 8.0500 NaN S [5 rows x 12 columns] The notna() conditional function returns a True for each row the values are not a Null value. As such, this can be combined with the selection brackets [] to filter the data table.
🌐
InterviewQs
interviewqs.com › ddi-code-snippets › rows-cols-python
Select rows from a Pandas DataFrame based on values in a column - InterviewQs
import pandas as pd · Create some ... 92, 95, 70]}df = pd.DataFrame(raw_data)df.head() #To select rows whose column value equals a scalar, some_value, use ==:df.loc[df['favorite_color'] == 'yellow'] #To select rows whose column value is in an iterable array, which we'll define ...
🌐
Statology
statology.org › home › pandas: select rows where two columns are equal
Pandas: Select Rows where Two Columns Are Equal
October 27, 2022 - You can use the following methods to select rows in a pandas DataFrame where two columns are (or are not) equal: ... import pandas as pd #create DataFrame df = pd.DataFrame({'painting': ['A', 'B', 'C', 'D', 'E', 'F'], 'rater1': ['Good', 'Good', 'Bad', 'Bad', 'Good', 'Good'], 'rater2': ['Good', 'Bad', 'Bad', 'Good', 'Good', 'Good']}) #view DataFrame print(df) painting rater1 rater2 0 A Good Good 1 B Good Bad 2 C Bad Bad 3 D Bad Good 4 E Good Good 5 F Good Good · We can use the following syntax to select only the rows in the DataFrame where the values in the rater1 and rater2 column are equal:
🌐
Arabpsychology
statistics.arabpsychology.com › psychological statistics › learning pandas: how to select rows based on equality of two columns
Learning Pandas: How To Select Rows Based On Equality Of Two Columns - PSYCHOLOGICAL STATISTICS
October 26, 2025 - Executing the operation is simple: we call df.query() and supply the expression 'rater1 == rater2'. Pandas executes this comparison row-wise, ensuring that only records where the string values in both columns are identical are included in the final result. The output below confirms that only ...
🌐
Bobby Hadz
bobbyhadz.com › blog › pandas-select-rows-where-two-columns-are-equal
Pandas: Select the Rows where two Columns are Equal | bobbyhadz
To select the rows where two columns are equal in a Pandas DataFrame: Use the DataFrame.loc indexer for indexing based on a boolean array. Specify a condition that compares the cell values of column A vs column B.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › how-to-select-rows-from-a-dataframe-based-on-column-values
How to Select Rows from a Dataframe based on Column Values ? - GeeksforGeeks
July 15, 2025 - The loc method is significant because it allows you to select rows based on labels and conditions. It is particularly useful when you need to filter data using specific criteria, such as selecting rows where a column value meets a certain condition.
🌐
Saturn Cloud
saturncloud.io › blog › pandas-tips-select-rows-by-column-value
How to select rows by column value in Pandas | Saturn Cloud Blog
September 10, 2023 - Finally, in some cases, Numpy methods can offer a faster alternative to Pandas methods, although at the cost of some readability: import numpy as np #select by scalar value data[data['Age'].values == 2] #select by iterable value data[np.in1d(data['Age'].values, [2, 5])] To wrap up, there are a variety of ways to select DataFrame rows by column value.
🌐
GeeksforGeeks
geeksforgeeks.org › selecting-rows-in-pandas-dataframe-based-on-conditions
Selecting rows in pandas DataFrame based on conditions - GeeksforGeeks
August 7, 2024 - 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.