Skip to content
Pandas

Indexing and Selecting

Select rows and columns with loc, iloc, and masks.

#indexing#loc#iloc

Code

pandas
import pandas as pd

df = pd.DataFrame({"name": ["A", "B", "C"], "age": [30, 25, 35]}, index=["x", "y", "z"])

# Label-based
row = df.loc["y"]
sub = df.loc[["x", "z"], ["name"]]
mask = df.loc[df["age"] > 28]

# Position-based
first = df.iloc[0]
block = df.iloc[:2, 1]
last_row = df.iloc[-1]

# Set and reset index
df2 = df.reset_index(drop=True)
df_idx = df.set_index("name")

# At for scalar
val = df.at["x", "age"]