Skip to main content
Albero Academy

Selecting & Filtering

Pick columns and rows, filter with boolean conditions, and use loc & iloc the right way — the most common pandas task.

Chapter 2Pandas15 min readBeginner friendly
  • #Pandas
  • #Filtering
  • #loc

Selecting the right slice of data — these columns, those rows — is what you do more than anything else in pandas. Get comfortable here and the rest of the library falls into place.

Selecting columns

columns
df["package"] # one column → a Series
df[["name", "package"]] # several columns → a DataFrame (note double [[]])
df["bonus"] = df["package"] * 0.1 # create a new column

Filtering rows

Boolean filtering is the heart of pandas — identical in spirit to NumPy masks. Build a condition, then index the DataFrame with it:

boolean filtering
# Everyone with a package above 7
df[df["package"] > 7]
# Combine conditions with & (and) | (or) — parenthesise each
df[(df["package"] > 6) & (df["programme"] == "Data")]
# Membership and text
df[df["programme"].isin(["Data", "Full Stack"])]
df[df["name"].str.startswith("A")]

loc vs iloc

Two accessors select rows and columns together. loc uses labels; iloc uses integer positions:

AccessorSelects byExample
locRow/column labelsdf.loc[0, "name"]
ilocInteger positionsdf.iloc[0, 1]
loc & iloc
df.loc[0, "name"] # label-based single cell
df.loc[df["package"] > 7, "name"] # filtered rows, one column — very common
df.loc[:, ["name", "package"]] # all rows, chosen columns
df.iloc[0] # first row (by position)
df.iloc[0:3, 0:2] # first 3 rows, first 2 columns

Sorting

sorting
df.sort_values("package", ascending=False) # top packages first
df.sort_values(["programme", "package"]) # by two keys
df.nlargest(5, "package") # shortcut for top 5

Practice

From your dataset: select two columns, filter to rows meeting two conditions (using &), use df.loc to read one column for the filtered rows, and get the top 5 rows by a numeric column with nlargest.

Key takeaways

  1. 01df["col"] selects one column (a Series); df[["a","b"]] selects several (a DataFrame).
  2. 02Filter rows with boolean conditions; combine with & and | inside parentheses.
  3. 03loc selects by label, iloc by integer position — loc[rows, cols] is the workhorse.
  4. 04Set values through .loc to avoid the chained-assignment trap.
  5. 05sort_values orders rows; nlargest/nsmallest grab the top/bottom n.