x = ['1', '2', '4', 'c'], so x[1]=='2', which makes the expression (x[0] != "1" and x[1] != "2" and x[2] != "3") be evaluated as False.

When conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True.

Answer from shiva on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › filtering list of objects on multiple conditions
r/learnpython on Reddit: Filtering list of objects on multiple conditions
July 27, 2023 - I had a thought that this might be easier to by creating something like a PlayerFilter class which can be instantiated and then have filters added to a dict attribute or similar, and then can be applied to a list of players and return the filtered list. This seems more Pythonic to me but also seems slightly overkill and I'm looking for the most straightforward and intuitive way to filter these values.
Top answer
1 of 4
10

x = ['1', '2', '4', 'c'], so x[1]=='2', which makes the expression (x[0] != "1" and x[1] != "2" and x[2] != "3") be evaluated as False.

When conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True.

2 of 4
8
['1', '2', '4', 'c']

Fails for condition

x[0] != "1"

as well as

x[1] != "2"

Instead of using or, I believe the more natural and readable way is:

lambda x: (x[0], x[1], x[2]) != ('1','2','3')

Out of curiosity, I compared three methods of, er... comparing, and the results were as expected: slicing lists was the slowest, using tuples was faster, and using boolean operators was the fastest. More precisely, the three approaches compared were

list_slice_compare = lambda x: x[:3] != [1,2,3]

tuple_compare = lambda x: (x[0],x[1],x[2]) != (1,2,3)

bool_op_compare = lambda x: x[0]!= 1 or x[1] != 2 or x[2]!= 3

And the results, respectively:

In [30]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; list_slice_compare = lambda x: x[:3] != [1,2,3]", stmt="list_slice_compare(rand_list)").repeat()
Out[30]: [0.3207617177499742, 0.3230015148823213, 0.31987868894918847]

In [31]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; tuple_compare = lambda x: (x[0],x[1],x[2]) != (1,2,3)", stmt="tuple_compare(rand_list)").repeat()
Out[31]: [0.2399928924012329, 0.23692036176475995, 0.2369164465619633]

In [32]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; bool_op_compare = lambda x: x[0]!= 1 or x[1] != 2 or x[2]!= 3", stmt="bool_op_compare(rand_list)").repeat()
Out[32]: [0.144389363900018, 0.1452672728203197, 0.1431527621755322]
Discussions

pandas - Filtering multiple conditions from a Dataframe in Python - Stack Overflow
I want to filter out data from a dataframe using multiple conditions using multiple columns. More on stackoverflow.com
🌐 stackoverflow.com
November 30, 2016
python - Pandas: Filtering multiple conditions - Stack Overflow
I'm trying to do boolean indexing with a couple conditions using Pandas. My original DataFrame is called df. If I perform the below, I get the expected result: temp = df[df["bin"] == 3] temp = t... More on stackoverflow.com
🌐 stackoverflow.com
conditional statements - Python : How to filter multiple conditions - Stack Overflow
I'm trying to filter multiple conditions, but every attempt I do is in vain. I want to filter every string (ex. Apple, Banana, stage, books etc), but the code just doesn't work as I expected. B = [] More on stackoverflow.com
🌐 stackoverflow.com
Python - Filter function with multiple conditions - Stack Overflow
I know this is a dummy question, but I didn't find the answer here the way I had in mind I just want to know if I can apply multiple filters within a single filter function A simple code to try it:... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › filter-pandas-dataframe-with-multiple-conditions
Filter Pandas Dataframe with multiple conditions - GeeksforGeeks
July 23, 2025 - DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 23 Jul, 2025 · In this article, let's discuss how to filter pandas dataframe with multiple conditions. There are possibilities of filtering data from Pandas dataframe with multiple conditions during the entire software development.
🌐
PäksTech
pakstech.com › blog › python-multiple-filter
Combine Multiple Filter Conditions in Python | PäksTech
October 3, 2022 - The built in filter() function loops through an iterable, in this case a list, and returns an iterator. Since we want the first item instead of an iterator we need to call the next() function to get the first result.
Find elsewhere
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas filter dataframe by multiple conditions
Pandas Filter DataFrame by Multiple Conditions - Spark By {Examples}
October 3, 2024 - How to Filter Pandas DataFrame by multiple conditions? By using df[], loc[], query(), eval() and numpy.where() we can filter Pandas DataFrame by multiple
🌐
Python Guides
pythonguides.com › pandas-filter-multiple-conditions
Filter DataFrames with Multiple Conditions in Python Pandas
May 5, 2026 - To filter a DataFrame based on more than one criterion, you need to use bitwise operators. In standard Python, we use and, or, and not. However, in Pandas, we use: ... I’ve learned the hard way that you must wrap each condition in parentheses ().
🌐
Saturn Cloud
saturncloud.io › blog › pandas-filtering-multiple-conditions
Pandas Filtering Multiple Conditions | Saturn Cloud Blog
May 1, 2026 - It accepts one or more Boolean conditions that evaluate to True or False. The Boolean conditions are combined using logical operators such as & (and) and | (or) to filter data based on multiple conditions.
🌐
Finxter
blog.finxter.com › home › learn python blog › python filter(lambda multiple conditions)
Python filter(lambda multiple conditions) - Be on the Right Side of Change
February 5, 2024 - The custom function is_even_and_gt_ten encapsulates the conditions. We then pass this function to filter(), which calls it for each element in the list. While less commonly used for filtering, Python’s functools.reduce() can be adapted to filter elements.
Top answer
1 of 3
1

You need:

fil_1 = test['col_a'].isin(['abc','def','ghi'])
fil_2 = test['col_b'].isin(['yes'])
fil_3 = test['col_c'].isin(['a'])

or

test.isin({'col_a': ['abc','def','ghi'],
           'col_b': ['yes'],
           'col_c' :['a']}).all(axis = 1)

df_filtered = test[fil_1 & fil_2 & fil_3]
print(df_filtered)
   col_a col_b col_c
0    abc   yes     a
2    abc   yes     a
4    def   yes     a
6    def   yes     a
8    ghi   yes     a
10   ghi   yes     a

or logic |

fil = test.isin({'col_a': ['abc','def','ghi'],'col_b': ['yes'],'col_c' :['a']})
df_filtered = df[fil]
print(df_filtered)

   col_a col_b col_c
0    abc   yes     a
1    abc   NaN   NaN
2    abc   yes     a
3    def   NaN   NaN
4    def   yes     a
5    def   NaN   NaN
6    def   yes     a
7    def   NaN   NaN
8    ghi   yes     a
9    ghi   NaN   NaN
10   ghi   yes     a

Now if we also use DataFrame.all:

df_filtered = df[fil.all(axis = 1)]
print(df_filtered)
   col_a col_b col_c
0    abc   yes     a
2    abc   yes     a
4    def   yes     a
6    def   yes     a
8    ghi   yes     a
10   ghi   yes     a

Detail

print(fil)
    col_a  col_b  col_c
0    True   True   True
1    True  False  False
2    True   True   True
3    True  False  False
4    True   True   True
5    True  False  False
6    True   True   True
7    True  False  False
8    True   True   True
9    True  False  False
10   True   True   True

print(test.isin({'col_a': ['abc','def','ghi']}))
    col_a  col_b  col_c
0    True  False  False
1    True  False  False
2    True  False  False
3    True  False  False
4    True  False  False
5    True  False  False
6    True  False  False
7    True  False  False
8    True  False  False
9    True  False  False
10   True  False  False

this return False in columns differences than col_a so you got NaN values ​​because you were using &

2 of 3
0

Here's the one-liner solution,

test[test.col_a.isin(['abc','def','ghi']) & test.col_b.isin(['yes']) & test.col_c.isin(['a'])]
Top answer
1 of 7
393

Pandas (and numpy) allow for boolean indexing, which will be much more efficient:

In [11]: df.loc[df['col1'] >= 1, 'col1']
Out[11]: 
1    1
2    2
Name: col1

In [12]: df[df['col1'] >= 1]
Out[12]: 
   col1  col2
1     1    11
2     2    12

In [13]: df[(df['col1'] >= 1) & (df['col1'] <=1 )]
Out[13]: 
   col1  col2
1     1    11

If you want to write helper functions for this, consider something along these lines:

In [14]: def b(x, col, op, n): 
             return op(x[col],n)

In [15]: def f(x, *b):
             return x[(np.logical_and(*b))]

In [16]: b1 = b(df, 'col1', ge, 1)

In [17]: b2 = b(df, 'col1', le, 1)

In [18]: f(df, b1, b2)
Out[18]: 
   col1  col2
1     1    11

Update: pandas 0.13 has a query method for these kind of use cases, assuming column names are valid identifiers the following works (and can be more efficient for large frames as it uses numexpr behind the scenes):

In [21]: df.query('col1 <= 1 & 1 <= col1')
Out[21]:
   col1  col2
1     1    11
2 of 7
65

Chaining conditions creates long lines, which are discouraged by PEP8. Using the .query method forces to use strings, which is powerful but unpythonic and not very dynamic.

Once each of the filters is in place, one approach could be:

import numpy as np
import functools
def conjunction(*conditions):
    return functools.reduce(np.logical_and, conditions)

c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4

data_filtered = data[conjunction(c_1,c_2,c_3)]

np.logical operates on and is fast, but does not take more than two arguments, which is handled by functools.reduce.

Note that this still has some redundancies:

  • Shortcutting does not happen on a global level
  • Each of the individual conditions runs on the whole initial data

Still, I expect this to be efficient enough for many applications and it is very readable. You can also make a disjunction (wherein only one of the conditions needs to be true) by using np.logical_or instead:

import numpy as np
import functools
def disjunction(*conditions):
    return functools.reduce(np.logical_or, conditions)

c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4

data_filtered = data[disjunction(c_1,c_2,c_3)]
🌐
Reddit
reddit.com › r/learnprogramming › multiple conditions in python filter function
r/learnprogramming on Reddit: Multiple conditions in python filter function
January 7, 2019 -

Question is to find all the prime numbers between two given numbers.

i made a 'list' of numbers between the two given number(let the 2 numbers be 1 and 100).

then i did this

l1=list(filter(lambda x:x!=2 and x%2,l))

where l is my list with all numbers.

output i got [1,3,5,6.....99]

shouldn't my output be [1,2,3....99]

🌐
Kanoki
kanoki.org › 2020 › 01 › 21 › pandas-dataframe-filter-with-multiple-conditions
Pandas dataframe filter with Multiple conditions | kanoki
January 21, 2020 - We are using the same multiple conditions here also to filter the rows from pur original dataframe with salary >= 100 and Football team starts with alphabet ‘S’ and Age is less than 60
🌐
Reddit
reddit.com › r/learnpython › pandas - filter based on multiple conditions
r/learnpython on Reddit: Pandas - Filter based on multiple conditions
January 17, 2021 -

Hi,

I have a csv file with approx. 100 columns and I want to filter rows if two of the columns are set to a value of X and the other columns are blank / Nan values. In order to make the code more readable, I would like to specify the column names in a list and then use the variable name within the Pandas query e.g. something like the following:

 

my_file=/home/test.csv
my_df=pd.read_csv(my_file)

control_fields=['Is_Active','Is_Valid']  
data_fields=['Age','DOB','Country','City']  

 

As a starting point, I have tried the following but this isn't filtering the data at all:

 

my_new_df=my_df[my_df['control_fields']==1]

 

Can someone please explain why the above isn't working and also advise if there is a better way of achieving my requirement?

Thanks!

🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
pandas: Select rows by multiple conditions | note.nkmk.me
August 8, 2023 - If you want to filter by partial matches, use the aforementioned string methods combined with & or |. print(df[df['name'].str.contains('li') | df['name'].str.endswith('k')]) # name age state point # 0 Alice 24 NY 64 # 2 Charlie 18 CA 70 # 5 Frank 30 NY 57 · source: pandas_multiple_conditions.py · In Python, the operator precedence is as follows: ~ has the highest priority, followed by &, and then |. 6.
🌐
Data Science Parichay
datascienceparichay.com › article › pandas-filter-dataframe-for-multiple-conditions
Pandas - Filter DataFrame for multiple conditions
Two thumbs up - I recently switched to WPX Hosting and recommend their speed, service and security - they do know what they are talking about when it comes to WordPress hosting.