Sub topic 10
Controlling what apply returns
This chapter assumes you know how Series.apply and DataFrame.apply call your function, and what axis=0 and axis=1 mean. It covers how the type your function returns decides the shape of the result, and how to steer that shape on purpose.
The rule: the return value decides the shape
apply collects whatever your function returns for each column, row, or element, then combines the pieces. It does not fix the result shape in advance. Three kinds of return value cover most cases:
- A scalar (a number, string, or boolean) becomes one cell in a Series.
- A
Seriesbecomes a row or column of a DataFrame. - A list, tuple, or array is kept as a single object in a cell, unless you ask for it to be expanded.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(lambda col: col.sum()))
print(df.apply(lambda col: col * 2))a 6
b 15
dtype: int64
a b
0 2 8
1 4 10
2 6 12The first call returns one scalar per column, so the result is a Series indexed by column name. The second returns a Series as long as the column, so the result is a DataFrame with the original shape.
Results by return type and axis
The same function can give different shapes depending on axis, because the labels come from different places.
| Function returns | `axis=0` (each column) | `axis=1` (each row) |
|---|---|---|
| Scalar | Series indexed by column labels | Series indexed by row labels |
| Series with new labels | DataFrame: those labels as the index, original columns as columns | DataFrame: original rows as the index, those labels as columns |
| Series with the same labels as the input | DataFrame with the original shape | DataFrame with the original shape |
| List, tuple, or array | Series of lists (object dtype) | Series of lists (object dtype) |
The following diagram shows how apply decides.
Returning a Series to build several outputs at once
Returning a named Series is the clearest way to compute several results from one pass over each row. The Series labels become the new column names.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
def spread(row):
return pd.Series({"total": row["a"] + row["b"], "diff": row["b"] - row["a"]})
result = df.apply(spread, axis=1)
print(result) total diff
0 5 3
1 7 3
2 9 3The result keeps the original row index, so you can assign it back with a list of column names:
df[["total", "diff"]] = df.apply(spread, axis=1)
print(df) a b total diff
0 1 4 5 3
1 2 5 7 3
2 3 6 9 3The assignment matches rows by index label, not by position. This is why apply is safe to use on a frame with a non-default index, as long as you do not reset or change the index in your function.
Returning lists and the result_type argument
A function that returns a list produces a Series of lists by default. That is usually not what you want:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(lambda row: [row["a"], row["b"]], axis=1))0 [1, 4]
1 [2, 5]
2 [3, 6]
dtype: objectDataFrame.apply has a result_type argument that overrides the default inference. It only has an effect with list-like results, and it applies to both axes.
| `result_type` | Effect |
|---|---|
| `None` (default) | Infer from the return value: scalars give a Series, Series give a DataFrame, lists give a Series of lists. |
| `"expand"` | List-like results become separate columns, numbered 0, 1, 2 and so on. |
| `"reduce"` | Return a Series if possible rather than expanding list-like results. This is the opposite of `"expand"`. |
| `"broadcast"` | List-like results are broadcast to the original shape, keeping the original index and columns. |
Use "expand" when the function returns a tuple and you want columns:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
expanded = df.apply(lambda row: (row["a"] + row["b"], row["b"] - row["a"]), axis=1, result_type="expand")
expanded.columns = ["total", "diff"]
print(expanded) total diff
0 5 3
1 7 3
2 9 3The columns arrive numbered, so you rename them afterwards. Returning a named Series avoids that step. Prefer the Series approach when you control the function, and "expand" when the function is shared or returns tuples already.
Series.apply can expand too
Series.apply follows the same principle. If the function returns scalars, you get a Series. If it returns a Series, you get a DataFrame:
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.apply(lambda x: pd.Series({"sq": x**2, "cube": x**3}))) sq cube
0 1 1
1 4 8
2 9 27This works but is slow, because it builds one small Series per element. The vectorized form gives the same output and is much faster on large data:
import pandas as pd
s = pd.Series([1, 2, 3])
print(pd.DataFrame({"sq": s**2, "cube": s**3}))If your function returns a list from Series.apply, you get a Series of lists. To turn that into columns, wrap the result: pd.DataFrame(result.tolist(), index=result.index).
How the result dtype is chosen
apply infers the dtype of the result from the returned values, the same way the Series constructor does. Three consequences follow:
- Returning ints gives
int64. Returning floats givesfloat64. - Returning a mix of numbers and
NoneorNaNgivesfloat64withNaNfor the missing entries. - Returning strings, lists, or mixed types gives
object.
A second effect applies to row-wise calls. With axis=1, each row is built as one Series, so it needs a single dtype. In a frame with both numbers and strings, the row becomes object:
import pandas as pd
df = pd.DataFrame({"name": ["a", "b"], "qty": [1, 2]})
print(df.apply(lambda row: str(row.dtype), axis=1))0 object
1 object
dtype: objectInside your function, row["qty"] is then a value from an object array, not a column of integers. Arithmetic still works, but numeric columns lose their specialized dtype while the function runs. In a frame of only floats and ints, the row is upcast to float64, which can change integers into floats in your function. To avoid the cost, select only the columns the function needs before applying: df[["price", "qty"]].apply(f, axis=1).
Inconsistent return values
The function should return the same kind of thing for every call. Mixing kinds is the most common source of confusing results.
A function that falls off the end without a return returns None. In an if without an else, the rows that skip the branch become None or NaN in the result. This is easy to miss in a long function, so check that every code path returns a value.
Controlling the cost with raw=True
By default each row or column reaches your function as a Series, which means building a Series object for every call. If your function only needs positional access to the values, set raw=True. Your function then receives a NumPy array instead:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(lambda values: values[0] + values[1], axis=1, raw=True))0 5
1 7
2 9
dtype: int64With raw=True the labels are gone, so you cannot write row["a"]. The result is also rebuilt from plain values, which is why it is only worth using when the function is simple and the frame is large. It does not make the function vectorized. Python still calls it once per row.
Choosing a shape deliberately
A short checklist helps when an apply result looks wrong:
- Print
type(result)andresult.shapeon a small sample before running on the full data. - Decide the shape you want first: one value per row (scalar), several named values per row (Series), or a transformed copy of the input (same-shape Series).
- Make your function return exactly that, with the same labels on every call.
- Use
result_type="expand"only when you cannot change a function that returns tuples or lists. - If you only need one column of the result, ask whether a vectorized expression can produce it without
apply.
Exercise
Given df = pd.DataFrame({"x": [1, 2, 3], "y": [10, 20, 30]}), what type does each call return, and what is its shape? (a) df.apply(lambda col: col.max()) (b) df.apply(lambda col: col / col.max()) (c) df.apply(lambda row: [row["x"], row["y"]], axis=1)
Show answer
(a) A Series of length 2, indexed by "x" and "y" (values 3 and 30), because the function returns one scalar per column. (b) A DataFrame of shape (3, 2), because the function returns a Series with the same labels as the input column. (c) A Series of length 3 with object dtype, where each element is a list, because lists are not expanded unless you pass result_type="expand".
Exercise
Write code that adds two new columns, "total" and "share", to df = pd.DataFrame({"a": [1, 3], "b": [3, 1]}). "total" is a + b for each row and "share" is a / total. Use a single apply call with axis=1 that returns a Series, and assign the result in one statement.
Show answer
def f(row):
total = row["a"] + row["b"]
return pd.Series({"total": total, "share": row["a"] / total})
df[["total", "share"]] = df.apply(f, axis=1)
The function returns a named Series, so apply builds a DataFrame with columns "total" and "share" and the original index, which can be assigned to two columns at once. The vectorized equivalent is df["total"] = df["a"] + df["b"] followed by df["share"] = df["a"] / df["total"], which is shorter and faster.