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
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 › 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 - This simple operation showcases power of pandas in filtering data efficiently. 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.
Discussions

python - How to find from which row and column the value belong? - Data Science Stack Exchange
Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 0 Comparing 2 columns from separate dataframes and copy some row values from one df to another if column value matches in pandas More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
April 23, 2020
How do you get the current row value from a pandas column
You needs axis=1 for row-based operations. You can also slice a subset of columns to have them all available. df = pd.DataFrame(dict( A = [1, 2, 3], B = [4, 5, 6] )) df[['A', 'B']].apply(lambda x: print(f"{x['A']=}", f"{x['B']=}"), axis=1) # x['A']=1 x['B']=4 # x['A']=2 x['B']=5 # x['A']=3 x['B']=6 However, having dictionaries as values sounds awkward. Perhaps you should be using .json_normalize at some stage to get a "flat" dataframe instead. More on reddit.com
🌐 r/learnpython
19
1
June 8, 2023
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
Pandas: Checking if a row exists with certain values
You can use boolean indexing to select only the rows where all the cells match matches = df[(df==a).all(axis=1)] to see which indexes match, just get the indexes of the new dataframe matches.index More on reddit.com
🌐 r/learnpython
5
4
July 1, 2016
People also ask

How do I search for a specific value in a pandas DataFrame column?
Use boolean indexing: df[df['column'] == value]. This returns all rows where the column equals the given value. For partial text matches, use df[df['column'].str.contains('substring', na=False)]. For checking membership in a list, use df[df['column'].isin([val1, val2])].
🌐
docs.kanaries.net
docs.kanaries.net › topics › Pandas › pandas-search-value-column
Pandas: Find and Filter Values in a DataFrame Column – Kanaries
How do I find and filter rows with missing values in pandas?
Use df[df['column'].isna()] to find rows where a column is NaN, and df[df['column'].notna()] to keep only non-null rows. To check across the entire DataFrame, use df[df.isna().any(axis=1)].
🌐
docs.kanaries.net
docs.kanaries.net › topics › Pandas › pandas-search-value-column
Pandas: Find and Filter Values in a DataFrame Column – Kanaries
How do I filter pandas DataFrame rows with multiple conditions?
Combine conditions using &amp; (AND), | (OR), and ~ (NOT) operators with parentheses: df[(df['A'] &gt; 10) &amp; (df['B'] == 'X')]. For cleaner syntax, use query(): df.query("A &gt; 10 and B == 'X'"). Do not use Python's and/or keywords.
🌐
docs.kanaries.net
docs.kanaries.net › topics › Pandas › pandas-search-value-column
Pandas: Find and Filter Values in a DataFrame Column – Kanaries
🌐
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
🌐
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 - This tutorial explains how to select rows based on column values in pandas, including several examples.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › get-a-specific-row-in-a-given-pandas-dataframe
Get a specific row in a given Pandas DataFrame - GeeksforGeeks
July 15, 2025 - In the Pandas Dataframe, we can find the specified row value with the function iloc(). In this function, we pass the row number as a parameter. The core idea behind this is simple: you access the rows by using their index or position.
🌐
Kanaries
docs.kanaries.net › topics › Pandas › pandas-search-value-column
Pandas: Find and Filter Values in a DataFrame Column – Kanaries
February 16, 2026 - You pass a condition inside square brackets, and pandas returns only the rows where that condition is True. # Find all orders from Alice alice_orders = df[df['customer'] == 'Alice'] print(alice_orders) You can use any standard comparison operator to filter by column value:
Find elsewhere
🌐
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 - Pandas.DataFrame.loc allows you to simply select rows by value: import pandas as pd data = pd.DataFrame({'Color': 'Tabby Black Calico Tabby Tabby Black'.split(), 'Name': 'Maxine Angel Delilah Tom Jeff Fluffy'.split(), 'Age': [2, 5, 17, 10, 7, 2]}) #select by scalar value data.loc[data['Color'] == 'Tabby'] #select by iterable value data.loc[data['Age'].isin([2, 5])] Boolean indexing also allows for selection by negation, or by multiple conditions (with &, |):
🌐
Pandas
pandas.pydata.org › docs › user_guide › indexing.html
Indexing and selecting data — pandas 3.0.6 documentation
Sometimes you want to extract a set of values given a sequence of row labels and column labels, this can be achieved by pandas.factorize and NumPy indexing.
🌐
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 - Let's assume that we want to select only rows with one specific value in a particular column. We can do so by simply using loc[] attribute: ... We can even omit loc and provide the boolean condition when indexing the pandas DataFrame as shown below:
🌐
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 dummy data · raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'], 'age': [20, 19, 22, 21], 'favorite_color': ['blue', 'blue', 'yellow', &quot;green&quot;], 'grade': [88, 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 as array, you can use isin:array = ['yellow', 'green']df.loc[df['favorite_color'].isin(array)] #To select a row base
🌐
Statology
statology.org › home › pandas: select rows where value appears in any column
Pandas: Select Rows Where Value Appears in Any Column
September 1, 2020 - The following syntax shows how to select all rows of the DataFrame that contain the values G or C in any of the columns: df[df.isin(['G', 'C']).any(axis=1)] points assists position 0 25 5 G 1 12 7 G 4 19 12 C · How to Filter a Pandas DataFrame on Multiple Conditions How to Find Unique Values in Multiple Columns in Pandas How to Get Row Numbers in a Pandas DataFrame
🌐
Saturn Cloud
saturncloud.io › blog › how-to-select-rows-from-a-dataframe-based-on-list-values-in-a-column-in-pandas
How to Select Rows from a DataFrame Based on List Values in a Column in Pandas | Saturn Cloud Blog
May 1, 2026 - We used the isin() method to create a Boolean mask that indicates whether each element of a DataFrame column is contained in a list of values, and then applied this mask to the DataFrame to select the desired rows. Pandas provides many other useful methods for data manipulation and analysis, making it a powerful tool for data scientists and software engineers.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-search-a-value-within-a-pandas-dataframe-row
How to search a value within a Pandas DataFrame row?
July 17, 2023 - import pandas as pd # Create a DataFrame data = {'Name': ['Shyam', 'Ranjan', 'Mohan', 'Raju', 'Dheeraj'], 'Age': [25, 32, 18, 22, 26], 'Designation': ['SDE', 'Tester', 'Web Developer', 'Intern', 'HR'], 'Salary': [50000, 17000, 26000, 20000, 17000]} df = pd.DataFrame(data) # Search for a value within a range of columns search_value = 17000 result = df.loc[df.loc[:, 'Age':'Salary'].eq(search_value).any(axis=1)] print(result) Name Age Designation Salary 1 Ranjan 32 Tester 17000 4 Dheeraj 26 HR 17000 · The apply() function with a lambda expression provides flexible row-wise searching ? import pan
🌐
Stack Exchange
datascience.stackexchange.com › questions › 72852 › how-to-find-from-which-row-and-column-the-value-belong
python - How to find from which row and column the value belong? - Data Science Stack Exchange
April 23, 2020 - Suppose I created the below data frame data = {'Height_1': [4.3,6.7,5.4,6.2], 'Height_2': [5.1, 6.9, 5.1, 5.2], 'Height_3': [4.9,6.2,6.5,6.4]} df = pd.DataFrame(data) Suppose s...
🌐
ProjectPro
projectpro.io › recipes › search-value-within-pandas-dataframe-row
Pandas find value in row - Find value in row pandas - Projectpro
December 23, 2022 - This recipe helps you search a value within a Pandas DataFrame row Last Updated: 23 Dec 2022
🌐
Saturn Cloud
saturncloud.io › blog › how-to-search-pandas-data-frame-by-index-value-and-value-in-any-column
How to Search Pandas Data Frame by Index Value and Value in Any Column | Saturn Cloud Blog
May 1, 2026 - We then set the index of the data frame to be the names column using the .set_index() method. Finally, we use the .loc[] method to search for rows with index value ‘Bob’. To search a pandas data frame by column value, you can also use boolean ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas find row values for column maximal
Pandas Find Row Values for Column Maximal - Spark By {Examples}
November 25, 2024 - In Pandas, you can find the row values for the maximum value in a specific column using the idxmax() function along with the column selection. You can
🌐
Reddit
reddit.com › r/learnpython › how do you get the current row value from a pandas column
r/learnpython on Reddit: How do you get the current row value from a pandas column
June 8, 2023 -

Hi, i've written a function that I want to apply to a pandas dataframe, but as an args, i need to pass the value of then neighbouring column, but I can't work out how to do that, it looks like I am passing the entire column by doing this:

df['A'] = df['A'].apply(key_check, args=df['B'])

Column A is a column of python dictionaries, and column B is a string value. How do I get the value of only the current row?

Here is the function I am trying to pass in:

def key_check(d={}, key=''):
new = {}
if not key:
    return 
if key in d:
    new[key] = d[key]
else:
    new[key] = ''
return new

currently it's returning the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

and I don't really understand what it means, I thought I was just passing a dictionary and a string to the apply function

🌐
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': ...