Find a course

Module 3: pandas: Working with TablesLesson 6 of 1214 min

Filtering, Sorting and Creating Columns

Filter rows with boolean conditions, sort by one or more columns, and add calculated columns with vectorized arithmetic, string methods and dates.

Step 1 of 11Learn

Filtering rows

Filtering in pandas uses the same boolean masks as NumPy. A comparison on a column returns a Series of True/False, and indexing the DataFrame with it keeps the True rows:

busy = df[df["bikes_out"] > 10]
harbor_morning = df[(df["station"] == "Harbor") & (df["hour"] < 10)]
weekend = df[df["day"].isin(["Sat", "Sun"])]
not_park = df[df["station"] != "Park"]

The same rules as NumPy apply: use &, | and ~, and wrap each condition in parentheses.

To filter rows and choose columns in one step, use .loc with a mask:

df.loc[df["bikes_out"] > 10, ["station", "hour"]]

.query() offers a readable string alternative: df.query("bikes_out > 10 and station == 'Harbor'").

Filtering returns a new DataFrame; the original is unchanged. If you filter and then want to modify the result, take a copy first, busy = df[df["bikes_out"] > 10].copy(), or you may see the famous SettingWithCopyWarning. It means pandas can't be sure whether you're editing the original data or a temporary copy, so your change might silently go nowhere. Recent pandas versions are moving to "copy-on-write" behavior that removes this ambiguity, but explicit copies remain a good habit.

Filtering keeps the rows where the mask is Truestationbikes_outHarbor14Market9Harbor6Park11> 10?TrueFalseFalseTruestationbikes_outHarbor14Park11df[df["bikes_out"] > 10]

Step 2 of 11Practice · Spot the mistake

Each line should keep rentals from the Harbor or Market stations with more than 5 bikes out. Click the lines that are wrong.

Step 3 of 11Learn

Sorting

sort_values orders rows by one or more columns:

df.sort_values("bikes_out")                          # ascending
df.sort_values("bikes_out", ascending=False)         # descending
df.sort_values(["station", "hour"])                  # by station, then hour within station
df.sort_values(["station", "bikes_out"], ascending=[True, False])

A few related tools:

  • df.nlargest(5, "bikes_out") and df.nsmallest(5, "bikes_out") get top or bottom rows directly.
  • df.sort_index() sorts by the index labels.
  • Missing values go to the end by default; na_position="first" changes that.

Remember from the last lesson: sorting keeps the original index labels. Add .reset_index(drop=True) if you want a clean 0, 1, 2... index afterwards.

Sorting also changes nothing in place unless you reassign: df = df.sort_values(...). Most pandas methods return a new object, and forgetting to assign the result is one of the most common "why didn't anything change?" bugs. Some methods accept inplace=True, but the pandas developers discourage it; reassigning is clearer and works with method chaining.

Step 4 of 11Practice · Code challenge · Python

Write top_n(records, key, n) that returns the n records with the largest value of key, highest first, like pandas' nlargest. Records are dictionaries. If two records tie, keep their original order.

Real Python, running in a sandbox in your browser.
  • top_n([{"s": "A", "b": 3}, {"s": "B", "b": 9}, {"s": "C", "b": 5}], "b", 2)
  • [r["s"] for r in top_n([{"s": "A", "b": 4}, {"s": "B", "b": 7}, {"s": "C", "b": 4}, {"s": "D", "b": 1}], "b", 3)]
  • top_n([{"s": "A", "b": 1}], "b", 5)

Step 5 of 11Learn

Creating columns

New columns are usually calculated from existing ones with vectorized arithmetic:

df["revenue"] = df["quantity"] * df["unit_price"]
df["price_with_tax"] = df["unit_price"] * 1.08
df["is_busy"] = df["bikes_out"] > 10
df["size"] = np.where(df["bikes_out"] > 10, "busy", "normal")

String methods live under the .str accessor and work on whole columns:

df["station"] = df["station"].str.strip().str.title()   # "  harbor " -> "Harbor"
df["is_downtown"] = df["station"].str.contains("Market|Harbor")
df["zip"] = df["address"].str.extract(r"(\d{5})")

Date parts live under .dt once a column is datetime:

df["start_time"] = pd.to_datetime(df["start_time"])
df["hour"] = df["start_time"].dt.hour
df["weekday"] = df["start_time"].dt.day_name()

.apply(func) runs any Python function on each value or row and is flexible, but it loops in Python, so it can be 10–100 times slower than vectorized code. Use built-in vectorized operations first, and apply only when no vectorized version exists.

To bin numbers into categories, pd.cut is ideal: pd.cut(df["age"], bins=[0, 18, 65, 120], labels=["minor", "adult", "senior"]).

A new column computed from existing columns, row by rowquantityunit_pricerevenue (new)24.59521011212df["revenue"] = df["quantity"] * df["unit_price"]

Step 6 of 11Practice · Work it out

A DataFrame has quantity = [2, 5, 1] and unit_price = [4.50, 2.00, 12.00]. After df["revenue"] = df["quantity"] * df["unit_price"], what is df["revenue"].sum()?

Step 7 of 11Learn

Method chaining for readable pipelines

pandas code becomes much easier to read when steps are written as a chain, each method feeding the next, inside parentheses so each step gets its own line:

morning_summary = (
    df
    .query("hour < 10")
    .assign(revenue=lambda d: d["minutes"] * 0.15)
    .groupby("station", as_index=False)
    .agg(rides=("revenue", "size"), revenue=("revenue", "sum"))
    .sort_values("revenue", ascending=False)
)

Read top to bottom, it tells a story: take the data, keep morning rides, add revenue, group by station, summarize, sort. There are no throwaway variables like df2, df3 and df_final_v2 to keep track of, and the original df is never modified.

Two methods make chaining work well. .assign() creates columns and returns a new DataFrame; the lambda d: form refers to the DataFrame at that point in the chain. .pipe(func) lets you insert your own function as a step.

When a chain misbehaves, debug it by commenting out steps from the bottom up, or temporarily ending it early to inspect the intermediate result. Chains are a style, not a requirement, but they make analyses far easier for others, and for you later, to review.

A method chain reads top to bottom as a pipelinedf.querymorning.assignrevenue.groupbystation.aggsum.sort_valueshighest first

Step 8 of 11Practice · Put in order

A chained pipeline should answer "total evening revenue per station, highest first". Put the steps in a sensible order.

Drag the items, or use the arrow buttons, to put them in order.

  1. Start from the full DataFrame
  2. Filter to evening rides with query
  3. Group by station and sum revenue
  4. Add a revenue column with assign
  5. Sort the totals from highest to lowest

Step 9 of 11Note

Step 10 of 11Note

Step 11 of 11Practice · Choose one

Which approach is usually fastest for creating df["total"] as quantity times price on a million-row DataFrame?