Data Science · Level 2 DataFrames

New Columns in pandas

Add a price-with-VAT column to a product table with one vectorized expression instead of looping over the rows.

  • df["new"] = expression
  • Arithmetic between columns
  • round() on a whole column

Assigning to a new column name creates it, computed for every row at once. Trap: looping with iterrows() works but is slow and wordy; write the column maths directly.

cart = pd.DataFrame({"price": [2.5, 10.0], "qty": [4, 1]})
cart["total"] = cart["price"] * cart["qty"]
cart["total"].tolist()   # [10.0, 10.0]

Write add_vat(df) that adds a with_vat column equal to price * 1.2, rounded to 2 decimals, and returns the DataFrame, for example a price of 10 gives 12.0.

solution.py
Test Suites Pending
Output