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
df["package"] # one column → a Seriesdf[["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:
# Everyone with a package above 7df[df["package"] > 7]# Combine conditions with & (and) | (or) — parenthesise eachdf[(df["package"] > 6) & (df["programme"] == "Data")]# Membership and textdf[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:
| Accessor | Selects by | Example |
|---|---|---|
loc | Row/column labels | df.loc[0, "name"] |
iloc | Integer positions | df.iloc[0, 1] |
df.loc[0, "name"] # label-based single celldf.loc[df["package"] > 7, "name"] # filtered rows, one column — very commondf.loc[:, ["name", "package"]] # all rows, chosen columnsdf.iloc[0] # first row (by position)df.iloc[0:3, 0:2] # first 3 rows, first 2 columns
Sorting
df.sort_values("package", ascending=False) # top packages firstdf.sort_values(["programme", "package"]) # by two keysdf.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
- 01df["col"] selects one column (a Series); df[["a","b"]] selects several (a DataFrame).
- 02Filter rows with boolean conditions; combine with & and | inside parentheses.
- 03loc selects by label, iloc by integer position — loc[rows, cols] is the workhorse.
- 04Set values through .loc to avoid the chained-assignment trap.
- 05sort_values orders rows; nlargest/nsmallest grab the top/bottom n.
