pandas: get rows (and index) matching a value
"Give me the rows where column X equals Y" is the first real pandas question everyone asks. The idiomatic answer is boolean indexing, and the official pandas reference documents the pieces behind it. This guide shows the pattern and the variants you will actually need.
The core pattern: boolean indexing
import pandas as pd
df = pd.DataFrame({
"name": ["ali", "sam", "rana"],
"city": ["gaza", "nablus", "gaza"],
})
matches = df[df["city"] == "gaza"]
df["city"] == "gaza" builds a boolean Series (True/False per row), and passing it back into df[...] keeps only the True rows. No loops, no filtering by hand.
Get the index labels of matching rows
idx = df.index[df["city"] == "gaza"] print(idx.tolist()) # [0, 2]
The Index object is pandas' axis label structure; the reference documents .tolist() to get plain Python values out of it.
Multiple conditions
Combine conditions with & (and) or | (or), with each condition in its own parentheses:
df[(df["city"] == "gaza") & (df["name"] != "ali")]
The parentheses are not decoration: & binds tighter than == in Python, so dropping them produces a confusing error.
isin for a list of values
df[df["city"].isin(["gaza", "ramallah"])]
Common mistakes
- Writing
and/orinstead of&/|; the plain keywords do not work element-wise on Series. - Comparing with
=(assignment) instead of==. - Expecting
df[df.col == x]to copy; it can be a view, so assign back with.locwhen editing.
Working with API data? Read and write JSON files in Python covers the format pandas pairs with most.
