HomeCourseModule 09 › Selecting rows and columns — loc and iloc

Selecting rows and columns — loc and iloc

Module 09 · Pandas Crash Course9 min readBeginner

What you'll learn

  • Select columns by name
  • Filter rows by condition
  • Use .loc and .iloc correctly

Selecting columns

df["name"]             # one column → Series
df[["name", "city"]]   # multi-column → DataFrame

Filtering rows by condition

df[df["age"] > 30]
df[df["city"] == "NYC"]
df[df["name"].str.startswith("A")]

Combining conditions

df[(df["age"] > 30) & (df["city"] == "NYC")]   # AND  — use &
df[(df["age"] < 30) | (df["city"] == "LA")]    # OR   — use |
df[~(df["city"] == "Chicago")]                  # NOT  — use ~

Important: use & | ~, not and/or/not. And wrap each condition in parentheses.

.loc — label-based selection

df.loc[0]                       # first row
df.loc[0:3, "name"]             # rows 0..3 (inclusive!), column 'name'
df.loc[df["age"] > 30, "name"]  # name column for the over-30s

.iloc — position-based selection

df.iloc[0]            # first row by position
df.iloc[:5, 0:2]      # first 5 rows, first 2 columns
df.iloc[-1]           # last row

The "is in this list" filter

df[df["city"].isin(["NYC", "LA"])]
df[~df["city"].isin(["NYC", "LA"])]   # everything not in the list

Walkthrough: pulling apart a dataset

The data

df = pd.read_csv("orders.csv")
df.columns
# Index(['order_id','date','region','customer','amount','status'])

Big orders in the North region

big_north = df[(df["region"] == "North") & (df["amount"] > 1000)]

Just two columns of those

big_north[["date", "amount"]]

Or in one go with .loc

df.loc[(df["region"]=="North") & (df["amount"]>1000),
       ["date", "amount"]]

Key takeaways

  • df[bool_mask] is the everyday filter pattern.
  • Use &, |, ~ (with parens) when combining.
  • .loc[rows, cols] for labels; .iloc[rows, cols] for positions.
  • .isin([list]) for membership filters.

Drill

From a DataFrame of employees: select everyone in Sales with a salary over $80k, returning only the name and salary columns.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.