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
๐ŸŒ
Medium
medium.com โ€บ @whyamit404 โ€บ pandas-where-column-equals-26503e95969a
Pandas Where Column Equals
April 21, 2025 - Ensure double equals == is used to check equality, not a single equal = which assigns value. Another mistake is neglecting to group conditions properly with parentheses. Remember, clarity is key! What does pandas where column equals mean?
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.equals.html
pandas.DataFrame.equals โ€” pandas 3.0.6 documentation
>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]}) >>> exactly_equal 1 2 0 10 20 >>> df.equals(exactly_equal) True ยท DataFrames df and different_column_type have the same element types and values, but have different types for the column labels, which will still return True.
Discussions

Python Pandas - select dataframe columns where equals - Stack Overflow
What is the Pandas equivalent of this SQL code? Select id, fname, lname from table where id = 123 I know that this is the equivalent of an SQL 'where' clause in Pandas: df[df['id']==123] And this More on stackoverflow.com
๐ŸŒ stackoverflow.com
[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
python - selecting columns equal to a field in pandas dataframe - Stack Overflow
My Pandas DataFrame looks like this: 0 STUN 1 Webex 2 PPP 3 MyVideo 4 Icecast 5 PPSTREAM 6 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 22, 2017
Python Pandas If value in column B = equals [X, Y, Z] replace column A with "T" - Stack Overflow
Say I have this array: A, B 1, G 2, X 3, F 4, Z 5, I If column B equals [X, Y or Z] replace column A with value "T" I've found how to change values within the same column but not across, any help... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
What is the difference between where() and boolean indexing in pandas?
Boolean indexing (df[df['col'] &gt; 5]) returns only rows that satisfy the condition. where() keeps the original DataFrame shape but replaces non-matching values with NaN. Use where() when you need to preserve index alignment.
๐ŸŒ
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
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  
๐ŸŒ
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 - Thank you for your question! 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.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.where.html
pandas.DataFrame.where โ€” pandas 3.0.6 documentation
>>> 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
Find elsewhere
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.DataFrame.equals.html
pandas.DataFrame.equals โ€” pandas 3.0.5 documentation
>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]}) >>> exactly_equal 1 2 0 10 20 >>> df.equals(exactly_equal) True ยท DataFrames df and different_column_type have the same element types and values, but have different types for the column labels, which will still return True.
๐ŸŒ
Kanaries
docs.kanaries.net โ€บ topics โ€บ Pandas โ€บ pandas-search-value-column
Pandas: Find and Filter Values in a DataFrame Column โ€“ Kanaries
February 16, 2026 - For strategies on handling missing data beyond filtering, see our pandas missing values guide and pandas fillna guide. Sometimes you need to find a value that could appear in any column of the DataFrame, not just one specific column. # Find rows where any column equals "Laptop" rows_with_laptop = df[df.eq('Laptop').any(axis=1)] print(rows_with_laptop)
๐ŸŒ
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ [pandas] if cell = x, get value from another column. otherwise, get value from previous row in that column.
r/learnpython on Reddit: [Pandas] If cell = x, get value from another column. Otherwise, get value from previous row in that column.
August 5, 2021 -

I'm a pretty heavy Excel user and trying to break out of that into some Python using Pandas. But things I could easily do in excel are not so straightforward to me in pandas. 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"

Any help is appreciated.

I have data that looks like this loaded into a pandas data frame:

Level Item
0 A
1 B
2 C
0 D
1 E
2 F

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 written to the previous row in New Column.

Example output:

Level Item New Column
0 A A
1 B A
2 C A
0 D D
1 E D
2 F D

My existing bad code.. I'm pretty sure this is not a very efficient way of doing this even if it worked.

for index in df.index[1:]:
    if df['Level'][index] == 0:
        df['New Column'][index] = df['Item'][index]
    else:
        df['New Column'][index] = df['Item'][index - 1]
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.DataFrame.where.html
pandas.DataFrame.where โ€” pandas 3.0.5 documentation
>>> 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
๐ŸŒ
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.
๐ŸŒ
Data to Fish
datatofish.com โ€บ if-condition-in-pandas-dataframe
Two Ways to Apply an If-Condition on a pandas DataFrame
Note that equality conditions need to have double equal signs, since you are checking for equality, and not assigning (single equal sign) a value. The output: Before: fish caught_count 0 salmon 100 1 pufferfish 5 2 shark 0 After: fish caught_count ge_100 0 salmon 100 True 1 pufferfish 10 False 2 shark 0 False ยท You can achieve the same by applying a lambda function instead: ... import pandas as pd data = {'fish': ['salmon', 'pufferfish', 'shark'], 'caught_count': [100, 5, 0] } df = pd.DataFrame(data) df['caught_count'] = df['fish'].apply(lambda x: 10 if x == "pufferfish") df['ge_100'] = df['caught_count'].apply(lambda x: True if x >= 100 else False)
๐ŸŒ
w3resource
w3resource.com โ€บ pandas โ€บ dataframe โ€บ dataframe-equals.php
Pandas DataFrame: equals() function - w3resource
August 19, 2022 - NaNs in the same location are considered equal. The column headers do not need to have the same type, but the elements within the columns must be the same dtype. ... Returns: bool True if all elements are the same in both objects, False otherwise.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ pandas โ€บ ref_df_equals.asp
Pandas DataFrame equals() Method
import pandas as pd data1 = { "name": ... Try it Yourself ยป ยท The duplicated() method compares two DataFrames and returns True if they are equal, in both shape and content, otherwise False....