Derived Columns

The column that answers your question usually is not in the file.

Arithmetic between columns

Columns combine row by row, so a rate, a total or a difference is one line.

import pandas as pd

df = pd.DataFrame({"price": [10.0, 20.0], "quantity": [3, 1]})
df["total"] = df["price"] * df["quantity"]
print(df["total"].tolist())

assign keeps the chain going

assign returns a new table with the column added, which is useful when you do not want to name an intermediate.

import pandas as pd

df = pd.DataFrame({"price": [10.0], "quantity": [2]})
out = df.assign(total=df["price"] * df["quantity"])
print(out["total"].tolist())

Exercise

Try It Yourself

Write percent_of_total(df) returning each row's amount as a percentage of the column total, rounded to one decimal place, as a list.

Press Run to see output

Check Your Understanding