We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Derived Columns

A derived column is a new column calculated from columns you already have. You create one simply by assigning to a new column name. Pandas runs the operation across the whole column at once, no loop required:

# df already contains a "subtotal" column
df["order_total"] = df["subtotal"] * 1.08 + 5
# now it also has an "order_total" column

It works like a spreadsheet formula that fills down every row. You can use any arithmetic, including combining multiple columns:

# Adding a "discount" column by subtracting
# the "sale_price" column from "list_price" column
df["discount"] = df["list_price"] - df["sale_price"]

Of course, it also works with text. You can concatenate text with +, which is handy for building labels:

# Add a "label" column by combining
# the "brand" and "category" columns with a hyphen in between
df["label"] = df["brand"] + "-" + df["category"]

Assigning to a column name that already exists replaces that column instead of adding a new one.

Assignment

SnackStack wants to flag how far each device drifts from its target temperature. Complete the add_temperature_deviation function. It accepts a DataFrame with "temperature" and "target_temperature" columns, and returns it with an added "temp_deviation" column.