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
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › ways-to-filter-pandas-dataframe-by-column-values
Filter Pandas Dataframe by Column Value - GeeksforGeeks
July 15, 2025 - This code filters the DataFrame to include only rows where the "Age" column has values of either 25 or 45. The .query() method allows you to filter a DataFrame using SQL-like syntax. This can be particularly useful when dealing with complex conditions. ... import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32,45], 'Score': [85, 90, 78]} df = pd.DataFrame(data) # Filter using query method where Age > 30 and Score < 90 filtered_df = df.query('Age > 30 and Score < 90') print(filtered_df)
🌐
Analytics Vidhya
analyticsvidhya.com › home › ways to filter pandas dataframe by column values
Ways to Filter Pandas DataFrame by Column Values
May 1, 2025 - Q2.How to filter a DataFrame based on a list of values? To filter a DataFrame based on a list of values in Pandas: Use .isin() on the column with your list to create a boolean mask.
Discussions

python - How do I select rows from a DataFrame based on column values? - Stack Overflow
You can also access variables in the environment by prepending an @. Copyexclude = ('red', 'orange') df.query('color not in @exclude') ... Save this answer. ... Show activity on this post. Since pandas >= 0.25.0 we can use the query method to filter dataframes with pandas methods and even column ... More on stackoverflow.com
🌐 stackoverflow.com
Filtering a pandas float column by “less than”
Can also do df = df.query(“column_name < 100.0”) IMO this is never a bad option since it’s extremely concise and clear. Anyone familiar with SQL, excel, etc will immediately understand what they’re looking at. More on reddit.com
🌐 r/learnpython
5
1
March 26, 2020
using pandas column value to filter columns.
Think about which dataframe you're referencing in your filtering and start with how you would do this operation if you were just passing a list of static values as columns to be selected into the new dataframe. Maybe you don't need to do this many operations to access the values you need. Also consider whether .isin is the best method to use here given that it returns booleans. Maybe .values is more appropriate to reference the items in the "new" series. More on reddit.com
🌐 r/learnpython
11
1
December 12, 2022
filter out rows in Pandas multi-level index dataframe

Based on your initial description it seems you want aggregation like this?:

>>> df
   A    B  value
0  1  1.0      1
1  2  2.0      2
2  3  3.0      3
3  3  4.0      4
4  1  5.0      5
5  3  NaN      6
>>> df.groupby('A').aggregate('max')
     B  value
A            
1  5.0      5
2  2.0      2
3  4.0      6

However I am not quite sure as it does not really match your desired output... can you clarify?

More on reddit.com
🌐 r/learnpython
6
4
October 17, 2016
🌐
Educative
educative.io › answers › how-to-filter-pandas-dataframe-by-column-value
How to filter pandas DataFrame by column value
isin() method: We can filter rows of a DataFrame based on whether the values in a specified column are present in a given list or array. ... To learn how we can apply a filter on the column values, let's first create a data example.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas filter by column value
Pandas Filter by Column Value - Spark By {Examples}
June 6, 2025 - Pandas support several ways to filter by column value, DataFrame.query() function is the most used to filter rows based on a specified expression,
🌐
GoLinuxCloud
golinuxcloud.com › home › databases › pandas › 7 ways to filter pandas dataframe by column value
7 ways to filter pandas DataFrame by column value | GoLinuxCloud
August 20, 2023 - To filter rows where a particular column has a non-missing value: ... You can combine the results from isna and notna for multiple columns using logical operators. For instance, to find rows where 'Age' is missing but 'Name' is present: ... Filtering data is a fundamental operation in data analysis and manipulation. Pandas, a powerful data manipulation library in Python, provides a plethora of methods to filter dataframes based on column values.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.filter.html
pandas.DataFrame.filter — pandas 3.0.6 documentation
>>> df = pd.DataFrame( ... np.array(([1, 2, 3], [4, 5, 6])), ... index=["mouse", "rabbit"], ... columns=["one", "two", "three"], ... ) >>> df one two three mouse 1 2 3 rabbit 4 5 6 · >>> # select columns by name >>> df.filter(items=["one", "three"]) one three mouse 1 3 rabbit 4 6
🌐
Codegive
codegive.com › blog › pandas_filter_by_column_value.php
Pandas Filter by Column Value: Unlock Data Insights & Master Your Datasets (2024 Guide)
To filter a pandas DataFrame by column value, use boolean indexing by providing a boolean Series (generated by a condition on a column) inside square brackets, or use the .loc[] accessor for explicit row and column selection. [/SNIPPET] [CONTENT] Filtering data is a fundamental operation in ...
Find elsewhere
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 filter rows of a pandas dataframe by column value
How to Filter rows of a Pandas DataFrame by Column Value | Towards Data Science
March 5, 2025 - I will walk through 2 ways of selective filtering of tabular data. To begin, I create a Python list of Booleans. I then write a for loop which iterates over the Pandas Series (a Series is a single column of the DataFrame). The Pandas Series, _Species_name_blast_hit_ is an iterable object, just like a list. I then use a basic regex expression in a conditional statement, and append either True if ‘bacterium’ was not in the Series value, or False if ‘bacterium’ was present.
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python pandas howtos" › "filter pandas dataframe rows by column values"
Filter Pandas DataFrame Rows by Column Values | Delft Stack
May 17, 2020 - When no rows match, pandas returns an empty DataFrame with the expected columns; it does not raise an exception. Check result.empty when an empty selection needs special handling. Conversely, a filter may return every row if a condition is too broad.
🌐
Tpoint Tech
tpointtech.com › ways-to-filter-pandas-dataframe-by-column-values-in-python
Ways to filter Pandas DataFrame by column values in Python - Tpoint Tech
April 15, 2026 - In this article, we've explored several methods to filter a DataFrame, including boolean indexing, the query method, the loc method, the isin method, combining filters, and the between method. By using these techniques, you can efficiently extract the data you need for your analysis.
🌐
Squash
squash.io › how-to-filter-dataframe-rows-based-on-column-values
How To Filter Dataframe Rows Based On Column Values
November 19, 2023 - Related Article: How to Find Maximum and Minimum Values for Ints in Python · One of the most common methods to filter dataframe rows based on column values in pandas is using boolean indexing.
🌐
Saturn Cloud
saturncloud.io › blog › how-to-filter-pandas-dataframes-by-column-of-strings
How to Filter Pandas DataFrames by Column of Strings | Saturn Cloud Blog
May 1, 2026 - To filter a DataFrame by a single string value in a column, we can use the str.contains() method. The str.contains() method returns a Boolean mask that can be used to select the rows that contain the specified string value in the column. import ...
🌐
Medium
medium.com › @agusabdulrahman › how-to-filter-a-pandas-dataframe-by-column-value-with-examples-4b5f5773c591
How to Filter a Pandas DataFrame by Column Value (With Examples) | by agus abdul rahman | Medium
March 14, 2025 - Filtering data is one of the most important tasks in data analysis. When working with large datasets in Pandas, you often need to extract specific rows based on column values. This tutorial will guide you through different ways to filter a Pandas DataFrame efficiently and effectively.
🌐
BrontoWise
brontowise.com › 2025 › 04 › 30 › filter-pandas-dataframe-by-column-values-all-possible-ways-brontowise
Filter Pandas DataFrame by Column Values – All Possible Ways | BrontoWise
May 10, 2026 - df_high_value_usa = df[df.apply(lambda row: row['Amount'] > 300 and row['Country'] == 'USA', axis=1)] print(df_high_value_usa) ... Now that you know all possible ways to filter pandas DataFrames, which method do you use the most? 🤔 Drop a comment below and let’s discuss! 👇 · ✨ Stay tuned for more Python tutorials at BrontoWise! ✨ 🚀 ... Like Loading... ... How to get clean ‘YYYYMMDD’ date strings from Snowflake DATE or TIMESTAMP columns without headache
🌐
Medium
medium.com › @debopamdeycse19 › how-to-filter-values-in-pandas-basic-to-advanced-methods-25b753ad74e5
How to Filter Values in Pandas- Basic to Advanced Methods | by Let's Decode | Medium
December 9, 2023 - For instance, if we have a DataFrame with customer data and we want to filter by both age and gender, we can use the following code: filtered_df = df[(df['age'] >= 25) & (df['gender'] == 'Female')] In Python ...
🌐
Built In
builtin.com › data-science › pandas-filter
How to Filter Pandas DataFrames | Built In
DataFrame image. | Screenshot: Soner Yildirim ... We can use the logical operators on column values to filter rows. ​ df[df.val > 0.5] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 4 Emily B ...
🌐
Medium
medium.com › swlh › 3-ways-to-filter-pandas-dataframe-by-column-values-dfb6609b31de
3 ways to filter Pandas DataFrame by column values | by Padhma Muniraj | The Startup | Medium
February 15, 2022 - Filtering is pretty candid here. You pick the column and match it with the value you want. A common confusion when it comes to filtering in Pandas is the use of conditional operators. Python syntax creates trouble for many.
🌐
Statology
statology.org › home › how to filter a pandas dataframe by column values
How to Filter a Pandas DataFrame by Column Values
March 11, 2021 - The following code shows how to filter the rows of the DataFrame based on values in a list · #define list of values value_list = [12, 19, 25] #return rows where points is in the list of values df.query('points in @value_list') team points assists rebounds 0 A 25 5 11 1 A 12 7 8 4 C 19 12 6 #return rows where points is not in the list of values df.query('points not in @value_list') team points assists rebounds 2 B 15 7 10 3 B 14 9 6 · How to Replace Values in Pandas How to Drop Rows with NaN Values in Pandas How to Drop Duplicate Rows in Pandas