Filter the DataFrame’s .index attribute using a boolean mask (df.index[df["col"] == value].tolist() or df[df["col"] == value].index.tolist()), or use np.flatnonzero(df["col"] == value) if you need zero-based integer positional indices (iloc) rather than DataFrame index labels (loc).
Basic Example
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"city": ["Lahore", "Karachi", "Lahore", "Islamabad", "Lahore"],
"score": [85, 92, 85, 78, 90],
},
index=["row_a", "row_b", "row_c", "row_d", "row_e"],
)
# 1. Get DataFrame INDEX LABELS where 'city' equals "Lahore"
matching_labels = df.index[df["city"] == "Lahore"].tolist()
print(matching_labels) # Output: ['row_a', 'row_c', 'row_e']
# 2. Get 0-based INTEGER POSITIONS (for .iloc) regardless of custom index labels
integer_positions = np.flatnonzero(df["city"] == "Lahore").tolist()
print(integer_positions) # Output: [0, 2, 4]
# 3. Get the FIRST matching index label safely (returns None if no match exists)
first_match = next(iter(df.index[df["city"] == "Lahore"]), None)
print(first_match) # Output: 'row_a'
Key Details & Edge Cases
- Index labels (
df.index[...]) vs. 0-based positional integers (np.flatnonzero(...)):- If your DataFrame has a default
RangeIndex(0, 1, 2, ...) with no dropped or reordered rows,df.index[mask]andnp.flatnonzero(mask)return identical integers. - Once rows have been filtered, sorted, or assigned string/date labels,
df.index[mask]returns the index labels (for use withdf.loc[...]), whereasnp.flatnonzero(mask)(ordf.index.get_indexer_for(df.index[mask])) returns 0-based integer positions (for use withdf.iloc[...]).
- If your DataFrame has a default
- Matching multiple values (
.isin([...])) or compound conditions (,|):- Multiple target values:
df.index[df["city"].isin(["Lahore", "Islamabad"])].tolist() - Compound conditions (wrap each condition in parentheses):
df.index[(df["city"] == "Lahore") & (df["score"] >= 90)].tolist()
- Multiple target values:
- Matching
NaN/ missing values (.isna()): Equality comparisons (df["col"] == np.nan) always returnFalsein Pandas. Use.isna()instead:df.index[df["col"].isna()].tolist(). - String matching (case-insensitive or substring): Use the
.straccessor withna=FalsesoNaNentries do not break indexing:# Case-insensitive exact match idx_ci = df.index[df["city"].str.lower() == "lahore"].tolist() # Substring match idx_sub = df.index[df["city"].str.contains("abad", na=False)].tolist() - Why
df.index[mask]is faster thandf[mask].index: Indexingdf.index[mask]directly subsets theIndexobject without constructing an intermediate filteredDataFramecopy in memory.
Comparison of Index Lookup Methods in Pandas
| Method | Syntax | Returns | Works With Custom/Non-Sequential Index? | Best Used When |
|---|---|---|---|---|
df.index[mask].tolist() |
df.index[df["col"] == val].tolist() |
list of index labels (loc) |
Yes (returns actual labels) | Retrieving index labels directly without building an intermediate DataFrame. |
np.flatnonzero(mask) |
np.flatnonzero(df["col"] == val).tolist() |
list of 0-based int positions (iloc) |
Yes (always 0-based positions) | Passing row positions into .iloc[] or NumPy arrays after sorting/filtering. |
next(iter(df.index[mask]), None) |
next(iter(df.index[df["col"] == val]), None) |
First matching label or None |
Yes | Finding the first matching row index safely without raising IndexError on empty matches. |
df.query(...).index.tolist() |
df.query("city == 'Lahore'").index.tolist() |
list of index labels (loc) |
Yes | Readable multi-column conditions inside method-chaining pipelines. |
You must log in or register to comment.