Sub topic 2
Series.apply
This chapter assumes you can write Python functions and lambdas, create pandas Series and DataFrame objects, and select or assign columns.
Series.apply
Series.apply calls a function for each value in a Series. It returns a new Series containing the results.
import pandas as pd
prices = pd.Series([10.0, 20.0, 30.0])
def add_tax(price, rate):
return price * (1 + rate)
taxed = prices.apply(add_tax, rate=0.2)
print(taxed)The function receives one value at a time. The original Series is unchanged unless you assign the result back to it.
Passing extra arguments to your function
Arguments after the function are passed to it as keyword arguments. This is useful when the same function needs different settings.
import pandas as pd
def label_price(price, currency):
return f"{currency}{price:.2f}"
prices = pd.Series([10, 20])
print(prices.apply(label_price, currency="$"))You can also use a lambda when the operation is short. For longer logic, a named function is easier to test and reuse.
map or apply: which one to use
Use map for a direct element-by-element transformation or lookup. Use apply when the function needs extra arguments or more general logic.
| Task | Recommended method |
|---|---|
| Replace each value with a dictionary lookup | `Series.map` |
| Transform each value with a simple function | `Series.map` |
| Call a function with extra parameters | `Series.apply` |
| Use several DataFrame columns together | `DataFrame.apply` |
A dictionary passed to map replaces matching values. Unmatched keys become missing values. For missing values passed to a function, map(..., na_action="ignore") can prevent the function from receiving them.
DataFrame.apply across columns and rows
DataFrame.apply sends one column or row to the function at a time. The default axis=0 processes columns. Use axis=1 to process rows.
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0],
"qty": [2, 3],
})
df["total"] = df.apply(
lambda row: row["price"] * row["qty"],
axis=1,
)
print(df)Returning a scalar for each row produces a Series. Returning a Series can produce a DataFrame. For this example, the vectorized expression df["price"] * df["qty"] is shorter and usually faster.
Exercise
Which method should you choose to multiply two DataFrame columns together, and why?
Show answer
Use a vectorized expression such as df["price"] * df["qty"]; it avoids the slower row-wise apply call.