ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Pandas Tutorial• 7 min read

Data Selection: loc, iloc & the query() Method

Label-based selection vs integer position-based slicing and boolean filtering

Pandas provides dedicated indexers: .loc[] for label-based indexing and .iloc[] for integer position-based indexing.

loc vs iloc Syntax

.loc[row_label, col_label]: Accesses rows and columns by text label or boolean condition. Crucially, label slices are endpoint-inclusive (loc["A":"C"] includes "C").

.iloc[row_pos, col_pos]: Accesses elements strictly by integer 0-indexed position. Integer slices are endpoint-exclusive (iloc[0:3] includes rows 0, 1, 2).

.query("expression"): Allows readable SQL-like filtering syntax directly on column names.

Comparing loc, iloc and query
import pandas as pd

df = pd.DataFrame({
    "city": ["New York", "London", "Tokyo", "Berlin"],
    "population": [8.4, 8.9, 13.9, 3.6],
    "continent": ["Americas", "Europe", "Asia", "Europe"]
}, index=["NYC", "LDN", "TKO", "BER"])

# 1. Label selection with .loc
print("NYC info (loc):
", df.loc["NYC", ["city", "population"]])

# 2. Integer position selection with .iloc
print("
First 2 rows (iloc):
", df.iloc[0:2, :])

# 3. Clean filtering with .query
european_cities = df.query("continent == 'Europe' and population > 5.0")
print("
European Mega-Cities:
", european_cities)
loc uses labels; iloc uses 0-based integer coordinates; query provides SQL-like filtering.
Pro Tip

Always avoid chained indexing like df["col"][0] = 5 because it causes the notorious SettingWithCopyWarning. Use df.loc[0, "col"] = 5 instead.

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which indexer must be used to select data using 0-based integer positions regardless of index labels?