How do I select rows with several conditions in pandas?
Keep the rows that meet one or several conditions with df[…] and .loc, combine tests with &, | and ~, use .isin(), compare .loc with .iloc, and change a selection safely with .copy().
After this lesson, you can keep the rows of a table that meet several conditions and change a selection without changing the table by accident.
How do I keep the rows that meet a condition?
A comparison on a column gives one True or False per row, and prices[condition] keeps the rows with True. prices.loc[condition, columns] also picks columns, with the rows before the comma and the columns after it. More than 15,000 shares traded on rows 1, 3, 4 and 5.
The example is a long panel of three made-up stocks on two days, with closes in dollars and volumes in shares. > is strict, so a volume of exactly 15,000 would fail.
The following box builds the panel and keeps the busy rows.
& keeps the rows that pass both tests, | those that pass at least one and ~ reverses a test. AAA with more than 15,000 shares is row 1 alone. .isin(["AAA", "CCC"]) tests whether each ticker is one of several, which replaces a chain of |.
Python runs & and | before == and >, so a comparison written inside a combination needs its own brackets. Without them, the selection raises a TypeError. A test stored under a name, such as busy, needs no brackets.
The following box combines the tests in three ways.
date ticker close volume
1 2026-03-03 AAA 102.0 18500
ticker volume
0 AAA 12000
How do .loc and .iloc differ?
.loc selects by row label and column name, and .iloc by position, counting from 0. A slice with .loc includes its end, so prices.loc[0:2] holds three rows, while prices.iloc[0:2] holds two.
After a selection, the labels and positions differ. CCC’s rows keep the labels 4 and 5, so ccc.loc[4, "close"] and ccc.iloc[0, 2] read the same price, and ccc.loc[0] would raise a KeyError.
.copy() makes a separate table, so changing it leaves the original as it was, and prices.loc[condition, column] = value writes into the original on purpose. Doubling AAA’s closes in a copy leaves prices with 101.2 and 102.0, and the .loc line marks the four busy rows in a new column.
Without .copy(), pandas 2.3 warns with a SettingWithCopyWarning. From pandas 3, a selection always behaves as a copy.
The following box changes a copy and then the original.