Posted in

How to filter a pandas DataFrame by multiple columns?

Hey there, data folks! Let’s cut to the chase—if you’ve ever sat staring at a messy pandas DataFrame, wondering how to pull exactly the slice of data you need across multiple columns, you’re not alone. I’ve been in your shoes, tripping over wrong filter syntax and wasting hours sifting through garbage data that didn’t fit my needs. And yeah, I run a filter supply company, but stick with me—this isn’t a sales pitch. It’s real, actionable pandas tips that I actually use for our own data team (you know, the people who source the industrial filters we sell? They need clean data too). Filter

Let’s start with the basics. Pandas is that Python library every data nerd swears by for wrangling tabular data, right? Its DataFrame is like a big, organized spreadsheet—except way cooler when you know how to filter it. Filtering by one column is easy (df[df[‘age’] > 30]), but when you add a second, third, or fifth condition? That’s where people start panicking. Over the years, my team and I have tested every trick in the book, and I’ve picked up hacks that actually work, no weird errors or syntax headaches.

First off, let’s get the core rule straight: when combining multiple conditions, you can’t use plain ‘and’ or ‘or’. Wait, why? Because pandas uses bitwise operators for vectorized operations, not Python’s logical operators. So ‘and’ becomes ‘&’ and ‘or’ becomes ‘|’—and super important: you HAVE to wrap each individual condition in parentheses. Skip the parens, and you’ll get a nasty TypeError that makes zero sense. Let’s test this with a real example that’s relevant to my work. Let’s say we have a DataFrame that tracks incoming filter shipments—columns like ‘filter_type’, ‘quantity’, ‘material’, ‘delivery_status’, and ‘warehouse_location’. Let’s say we want to pull all shipments where:

  1. They’re HEPA filters (‘filter_type’ == ‘HEPA’)
  2. Quantity is over 100 (‘quantity’ > 100)
  3. They’re not marked “damaged” (‘delivery_status’ != ‘damaged’)

That’s three conditions, all across different columns. Let’s write that first try, the wrong way, to show you what not to do:
bad_filter = df[df[‘filter_type’] == ‘HEPA’ and df[‘quantity’] > 100 and df[‘delivery_status’] != ‘damaged’]
If you run that, you’ll get a TypeError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Which is basically pandas yelling at you for forgetting parentheses and using ‘and’ instead of ‘&’. The corrected version works like a charm:
good_filter = df[(df[‘filter_type’] == ‘HEPA’) & (df[‘quantity’] > 100) & (df[‘delivery_status’] != ‘damaged’)]
Boom. That’s simple, right? No extra libraries, no complicated syntax—just parens and bitwise operators. I use this exact line every week to pull shipment data for our warehouse team.

But wait, what if you have more conditions? Or conditions that are ranges, or multiple values in one column? That’s where things get flexible. Let’s say instead of just HEPA, we want HEPA and activated carbon filters, plus shipments over 50 and under 200, plus only locations in Chicago or Dallas. That’s where .isin() comes in—way cleaner than writing 5 separate equality checks. Let’s rewrite that:
multi_col_filter = df[(df[‘filter_type’].isin([‘HEPA’, ‘activated_carbon’])) &
(df[‘quantity’].between(50, 200)) &
(df[‘warehouse_location’].isin([‘Chicago’, ‘Dallas’]))]
See how much cleaner that is? Instead of typing (df[‘filter_type’] == ‘HEPA’) | (df[‘filter_type’] == ‘activated_carbon’), which also works but gets messy fast when you have 10 values, .isin() is perfect for when you want a column to match any of a list of values. And .between() is a lifesaver for range checks—no need for (df[‘quantity’] >=50) & (df[‘quantity’] <=200), though that works too, .between() is just more readable. My team uses this when we’re auditing our inventory levels across different warehouse zones.

Now, let’s talk about when this gets more advanced, like if you need to filter columns where values are null? Or if you want to combine string conditions? Let’s say we want all filter materials that start with “poly” and have a delivery note that mentions “inspected”. We can use .str.contains() for string conditions, and combine it with our bitwise operators:
string_filter = df[(df[‘material’].str.startswith(‘poly’)) &
(df[‘delivery_notes’].str.contains(‘inspected’, na=False))]
The na=False part is important here—it skips null values in ‘delivery_notes’ instead of throwing an error, which saves so much debugging time. I almost forgot that a few months ago, when a shipment had a missing delivery note and the whole filter broke—now I never skip that parameter.

Wait, what if you’re working with really large DataFrames? Like, we’re talking hundreds of thousands of shipment records, not just a tiny test set. The methods above are all vectorized operations, which means they’re fast—way faster than looping through each row in Python. I’ve tested it: a loop would take 10 minutes to filter 500k rows, but the vectorized method takes less than a second. That’s a game-changer for my data team, who have to pull real-time inventory data for sales and operations.

Now, let’s chat about a common pitfall: the all-vs-any mistake. If you’re using .isin() or multiple conditions, remember that ‘&’ is “all conditions must be true” (that’s pandas’ version of ‘and’) and ‘|’ is “any condition can be true” (pandas’ version of ‘or’). I see people mix these up all the time—last month, a new intern at my company ran a filter that used ‘|’ instead of ‘&’ for the shipment conditions, and they accidentally pulled in 2x more orders than needed, leading to extra warehouse pullers working overtime. Oops. So always double-check which operator you’re using, depending on if you want all conditions met or just any.

Another trick: if you have a ton of conditions, and writing them all in one line gets messy, you can use query() method. That’s another way to filter multiple columns, and it reads almost like plain English. Let’s take our original HEPA filter example and rewrite it with query():
query_filter = df.query("filter_type == ‘HEPA’ & quantity > 100 & delivery_status != ‘damaged’")
That’s way more readable, right? Like, almost no pandas syntax to learn—just write the conditions as a string. It’s especially helpful for people who are new to pandas, or when you have a lot of conditions and don’t want to stare at a wall of parentheses. The downside? It’s slightly slower than the bracket method for super large DataFrames, but for most use cases, it’s totally fine. I use query() when I’m sharing code with non-technical stakeholders, because it’s easier for them to follow along.

Let’s put this all together with a real, full example from our work. Suppose our filter shipment DataFrame looks like this:
filter_type | quantity | material | delivery_status | warehouse_location | delivery_notes
HEPA | 120 | fiberglass | good | Chicago | inspected
activated_carbon | 80 | carbon | good | Dallas | inspected
HEPA | 50 | fiberglass | damaged | Chicago | needs replacement
activated_carbon | 200 | carbon | good | Austin | no notes
HEPA | 150 | pete | good | Dallas | inspected

If we use our first bracket method:
result = df[(df[‘filter_type’] == ‘HEPA’) & (df[‘quantity’] > 100) & (df[‘delivery_status’] != ‘damaged’)]
What do we get? Only the last row: HEPA filters, 150 quantity, good status, Dallas location. That’s exactly what we wanted. If we used the .isin() method for a broader pull, we’d get all HEPA or activated carbon filters over 50, in Chicago or Dallas, and so on.

Now, a quick note: I’m not here to sell you a filter, but here’s the thing—just like how we make industrial filters that stop exactly what you don’t want (dust, debris, contaminants), pandas filter functions stop exactly the data you don’t need. Both are about precision, right? If you’ve ever struggled with messy data or inefficient filtering for your work, we at our filter supply company know how important precision is—whether it’s a air filter for a factory, or a data filter for your DataFrame.

Wait, before you go, a couple of quick best practices to wrap this up: 1) Always test your filters on a small subset of data first, not the whole dataset. That way, if you make a mistake, you don’t waste time or mess up big datasets. 2) Name your filtered DataFrames something obvious, like hepa_filter_100, not temp or result—you’ll thank yourself later when you’re going back to code from a week ago. 3) If you’re working with pandas 1.0+, all these methods work seamlessly—no need for outdated versions.

If you’re tired of fumbling with messy data, or need help building precise filters for your datasets (or even industrial filters for your operations, if that’s your thing), we’re here to help. Reach out to our team to discuss your needs, whether you’re filtering shipment data for inventory or sourcing high-performance filters that meet your exact specs.

Oil Filter Element References:
Wes McKinney. Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython. O’Reilly Media, 2022.
Pandas Documentation: Indexing and Selecting Data. pandas.pydata.org, accessed 2024.
Julia Evans. “Pandas Gotchas.” Julia Evans Blog, 2023.


Xinxiang Deshengwei Filtration and Purification Equipment Co., Ltd.
As one of the most experienced filter suppliers in China, we also support customized service. We warmly welcome you to buy bulk high quality filter made in China here from our factory. If you have any enquiry about cooperation, please feel free to email us.
Address: No.5 Daoqing Road, Hongqi District, Xinxiang City, Henan Province, China.
E-mail: rushufeng@dswgl.com
WebSite: https://www.dswfiltration.com/