Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Adding a Computed Column
Arithmetic on a column applies to every row at once, with no loop:
df["total"] = df["price"] * df["quantity"] df["price_with_tax"] = df["price"] * 1.2
This is vectorised. Writing a Python loop over rows to do the same thing is typically fifty times slower and much longer, and df.iterrows() in particular is a smell: almost every use of it can be replaced by column arithmetic.
Two columns line up by their index, not by position. That matters as soon as you have filtered or sorted one of them: pandas aligns on the labels and fills anything unmatched with NaN, which is usually a helpful surprise and occasionally a baffling one.
Assigning to a filtered frame is where the SettingWithCopyWarning comes from:
subset = df[df["price"] > 10] subset["flag"] = True # warns: subset may be a view or a copy subset = df[df["price"] > 10].copy() # be explicit, no warning
Your task:
Write add_total(df) that adds a "total" column equal to price * quantity, and returns the DataFrame.
Example Tests
The new column holds price times quantity for each row
Input: {"df":{"price":[2,3],"quantity":[4,5]}}
Expected: [8,15]
The frame gains exactly one column
Input: {"df":{"price":[1],"quantity":[1]}}
Expected: [1,3]
A quantity of zero gives a total of zero, not a dropped row
Input: {"df":{"price":[5,5],"quantity":[0,2]}}
Expected: [0,10]
import pandas as pd
def add_total(df):
"""
Add a "total" column of price * quantity.
Args:
df: a DataFrame with "price" and "quantity" columns
Returns:
The DataFrame with the extra column.
"""
# YOUR CODE HERE
pass
def _run(df):
import pandas as pd
return add_total(pd.DataFrame(df))
def _totals(df):
import pandas as pd
return [float(v) for v in add_total(pd.DataFrame(df))["total"]]Run your code to see results
⌘↵ runs against the visible tests