Sub topic 10
Controlling what apply returns
This chapter assumes you can write Python functions and lambdas, build a pandas Series and DataFrame, and assign new columns. You have already seen Series.apply and DataFrame.apply. Here you will learn how the value your function returns decides the shape of the result.
The rule: what you return sets the shape
apply collects whatever your function returns for each element, row, or column, then tries to assemble those pieces into one object. The type of each piece decides the outcome.
- Return a scalar (a single number or string) and you get a Series.
- Return a Series and you get a DataFrame, with each returned Series becoming a column or a row.
The table below summarizes DataFrame.apply.
| Call | Function receives | Function returns | Result |
|---|---|---|---|
| `df.apply(f)` (axis=0) | one column | scalar | Series indexed by column name |
| `df.apply(f)` (axis=0) | one column | Series | DataFrame, one column per input column |
| `df.apply(f, axis=1)` | one row | scalar | Series indexed like the rows |
| `df.apply(f, axis=1)` | one row | Series | DataFrame, one row per input row |
Returning a scalar
A scalar return reduces each column or row to one value. This example computes the range of each column.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(lambda col: col.max() - col.min()))The output is a Series with the index a and b, and the value 2 for both.
Returning a Series
When the function returns a Series, the index labels of that Series become the labels on the other axis of the result. This example returns two statistics per column.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
summary = df.apply(lambda col: pd.Series({"min": col.min(), "max": col.max()}))
print(summary)The result has the rows min and max and the columns a and b. Each returned Series became one column.
With axis=1, the same idea builds new columns from each row.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
extra = df.apply(
lambda row: pd.Series({"total": row["price"] * row["qty"], "big": row["price"] > 15}),
axis=1,
)
print(df.join(extra))Here each row produces a Series with two labels, total and big. Those labels become the new column names, and join attaches them to the original data.
Using result_type with axis=1
With axis=1, you can steer the shape using result_type.
"expand"turns list-like results into separate columns."reduce"tries to return a Series instead of a DataFrame."broadcast"keeps the original shape and index, filling the original columns with the returned values.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0], "qty": [1, 2]})
out = df.apply(lambda row: [row["price"] * row["qty"], row["qty"] * 2], axis=1, result_type="expand")
print(out)The list returned for each row becomes two columns, numbered 0 and 1. Rename them with out.columns = ["total", "double_qty"].
Common errors
- Inconsistent returns. If the function returns a scalar for some rows and a Series for others, the result can be a Series of objects instead of a clean DataFrame. Make the function return the same type every time.
- Mismatched labels. If the returned Series have different index labels, the result gets the union of all labels and fills the gaps with
NaN. Return the same labels each time. - Returning a list without
result_type. Withaxis=1, a list is kept as a single object in each cell of a Series. Useresult_type="expand"or return a Series to get separate columns. - Assigning a DataFrame to one column.
df["x"] = df.apply(f, axis=1)fails or gives odd results iffreturns a Series. Assign to several columns withdf[["x", "y"]] = ...or usejoin.
Exercise
Given df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}), what shape is the result of df.apply(lambda col: pd.Series({"first": col.iloc[0], "last": col.iloc[-1]}))? Which labels does it have on each axis?
Show answer
The function returns a Series for each column, so the result is a DataFrame with 2 rows and 2 columns. The row labels are "first" and "last" (the index of the returned Series), and the column labels are "a" and "b" (the original column names). The values are first = 1 and 4, last = 3 and 6.
Exercise
A row-wise apply returns [x, y] as a list for each row, and the result is a Series of lists. Name two ways to get x and y as separate columns.
Show answer
Pass result_type="expand" to df.apply(..., axis=1), or return pd.Series({"x": x, "y": y}) from the function instead of a list.