Sub topic 2
Selecting Rows and Columns with `.iloc` in pandas
Assume you know basic Python slices and can create a pandas DataFrame. iloc selects by integer position. Row position 0 means the first row, and column position 0 means the first column.
Selecting with `.iloc`
Use .iloc[row_selector, column_selector]. Integer slices exclude their stop value, just like ordinary Python slices.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
print(df.iloc[1:4, [0, 1]]) # rows 1, 2, 3; columns 0 and 1
print(df.iloc[0, 2]) # one value: "Europe"The first expression includes row positions 1 through 3, but not 4. Lists select specific positions. A single integer selects one row or column.
Filtering Rows with Boolean Masks
A boolean mask is a sequence of True and False values aligned with the rows. Applying it inside brackets keeps the rows marked True.
large = df["population_k"] > 3000
print(df[large])Combining Conditions
Use & for “and,” | for “or,” and ~ for “not.” Put each comparison in parentheses. Python’s and and or do not work for element-by-element pandas conditions.
large = df["population_k"] > 3000
south_america = df["continent"] == "South America"
print(df[large & south_america])
print(df[large | south_america])
print(df[~large])Helpers for Common Filters
isin tests membership. between tests an inclusive numeric range. The .str accessor applies string methods to each value.
print(df[df["continent"].isin(["Asia", "Africa"])])
print(df[df["population_k"].between(2500, 5000)])
print(df[df["city"].str.startswith("Q")])Exercise
What rows does df.iloc[1:3, [0, 2]] return?
Show answer
Rows at positions 1 and 2, with columns at positions 0 and 2. The stop position 3 is excluded.