Sub topic 8
DataFrame.apply across columns and rows
This chapter assumes you can write Python functions and lambdas, build a DataFrame, select columns, and assign new ones. You should also know how Series.map and Series.apply behave on a single column. Here you will learn what DataFrame.apply hands to your function, how axis changes that, and how the function's return value decides the shape of the result.
What apply passes to your function
DataFrame.apply(func, axis=0) calls func once per column or once per row. Each call receives a whole Series, not a single value. This is the main difference from Series.map and from DataFrame.map, which work one cell at a time.
The axis argument names the direction in which the function slides:
axis=0(also"index", the default): the function receives one column at a time. The Series index is the DataFrame's row labels, and the Seriesnameis the column label.axis=1(also"columns"): the function receives one row at a time. The Series index is the DataFrame's column labels, and the Seriesnameis the row label.
The wording is easy to misread. axis=0 means "move down the rows", so the function sees columns. axis=1 means "move across the columns", so the function sees rows.
Applying a function to each column
With the default axis=0, a function that returns one number per column produces a Series indexed by column label.
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0, 30.0],
"qty": [1, 2, 3],
})
spread = df.apply(lambda col: col.max() - col.min())
print(spread)The output is:
price 20.0
qty 2.0
dtype: float64Each result is a scalar, so pandas collects the scalars into a Series. The qty value became 2.0 because the Series holds both results and needs one common dtype.
If the function returns a Series for each column, pandas lines those Series up side by side as columns of a new DataFrame.
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) a b
min 1 4
max 3 6The index of the returned Series (min, max) becomes the row index of the result. The original column labels stay as the columns.
Applying a function to each row
Set axis=1 when the logic needs several columns of the same row.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
df["total"] = df.apply(lambda row: row["price"] * row["qty"], axis=1)
print(df)Inside the lambda, row is a Series. You read values with row["price"], the same way you would read from any labeled Series. The result is a Series aligned to the original index, so assigning it to a new column works.
Rows can change dtypes
A row mixes the values of different columns into one Series, and a Series has a single dtype. pandas picks a common type for the row.
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0, 30.0],
"qty": [1, 2, 3],
"item": ["pen", "book", "bag"],
})
print(df[["price", "qty"]].apply(lambda row: row.dtype, axis=1))
print(df.apply(lambda row: row.dtype, axis=1))In the first call every row has dtype float64, so qty is silently converted to a float inside your function. In the second call the text column forces every row to object. Numbers in an object row are still numbers, but arithmetic on them is slower and some NumPy functions behave differently. Select only the columns you need before applying row-wise:
df[["price", "qty"]].apply(my_function, axis=1)This keeps the dtype narrow and makes the function's dependencies visible.
Passing extra arguments
Extra positional and keyword arguments after func are forwarded to your function, as in Series.apply. This lets you write a normal named function and reuse it.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
def label(row, threshold):
return "bulk" if row["qty"] >= threshold else "single"
df["kind"] = df.apply(label, axis=1, threshold=2)
print(df["kind"].tolist())The printed list is ['single', 'bulk', 'bulk']. Pass args=(...) for a tuple of positional arguments. Do not name your own keyword axis, raw, result_type or args, because apply consumes those names itself.
Controlling the result shape
The value your function returns for each row or column decides the shape of the final result.
| Function returns | `axis=0` result | `axis=1` result |
|---|---|---|
| A scalar | Series indexed by column label | Series indexed by row label |
| A Series | DataFrame; the returned index becomes the row labels | DataFrame; the returned index becomes the column labels |
| A list or tuple | Series of lists (default) | Series of lists (default) |
| A list with `result_type="expand"` | Columns hold the list items | Columns hold the list items |
The default for list-likes is a Series whose cells are lists, which is rarely what you want. result_type changes this:
"expand": list-like results become separate columns, numbered from 0."reduce": tries to return a Series instead of expanding, the opposite of"expand"."broadcast": results keep the original shape and labels of the DataFrame.
Here is "expand" in use:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
out = df.apply(
lambda row: [row["a"] + row["b"], row["a"] * row["b"]],
axis=1,
result_type="expand",
)
out.columns = ["total", "product"]
print(out) total product
0 5 4
1 7 10
2 9 18Returning a Series with named labels gives the same shape and names the columns for you:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
out = df.apply(
lambda row: pd.Series({"sum": row["a"] + row["b"], "diff": row["a"] - row["b"]}),
axis=1,
)
print(out)This is clearer, but it builds one Series object per row, which is the slowest option in this chapter.
raw=True: skipping the Series
By default pandas builds a Series for every row or column. With raw=True it passes a plain NumPy array instead. This skips the Series construction and can be noticeably faster, but you lose labels and must index by position.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(lambda arr: arr[0] * arr[1], axis=1, raw=True))The result is a Series with the values 4, 10 and 18. Use raw=True only when the function already works on arrays and does not need row["a"] style access. It also makes the code depend on column order, which breaks silently if columns are reordered.
Prefer a vectorized expression
Row-wise apply runs Python code once per row. The price-times-quantity example above can be written without any per-row Python call:
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
df["total"] = df["price"] * df["qty"]
print(df)The result is identical, the code is shorter, and the work runs in compiled code across whole columns. The gap grows with the number of rows. Conditional logic that seems to need a function usually has a vectorized form too:
import numpy as np
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
df["kind"] = np.where(df["qty"] >= 2, "bulk", "single")
print(df["kind"].tolist())Reach for axis=1 when the per-row logic is truly irregular. Examples are parsing a string that depends on another column, calling a function from an outside library that accepts one record at a time, or branching in ways that arithmetic and np.where cannot express.
Column-wise apply with axis=0 has a smaller cost. It makes one call per column, so the call count stays small even on a table with millions of rows. The function usually calls vectorized Series methods internally. For simple reductions, a built-in such as df.max() - df.min() is shorter still.
Common errors
- Forgetting
axis=1.df.apply(lambda row: row["price"] * row["qty"])raises aKeyError, because the function receives columns and"price"is not an index label of a column. Check the direction first. - Assigning a DataFrame to one column. If your function returns a Series per row, the result is a DataFrame. Assigning it to
df["x"]fails or gives unexpected output. Return a scalar for one new column. - Mutating the row. Changing
row["a"]inside the function does not reliably change the original DataFrame, becauserowmay be a copy. Return the new value and assign it yourself. - Relying on position. Code like
row[0]on a labeled row is deprecated in recent pandas versions. Userow.iloc[0]or, better, the label. - Mixed dtypes. A row that contains text becomes an
objectSeries. Select the numeric columns first. - Printing for debugging.
printinside the function runs once per row, which can flood the console. Test ondf.head(3)first.
Exercise
Given df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}), write one call that adds a column "ratio" holding a / b for each row using DataFrame.apply, then write the vectorized equivalent. Which direction does the function slide, and what does the function receive?
Show answer
Row-wise: df["ratio"] = df.apply(lambda row: row["a"] / row["b"], axis=1). Vectorized: df["ratio"] = df["a"] / df["b"]. With axis=1 the function slides across the columns, so it receives one row per call as a Series whose index is ["a", "b"] and whose name is the row label.
Exercise
A function passed to df.apply(f) with the default axis returns pd.Series({"min": col.min(), "max": col.max()}) for each column. What are the row labels and column labels of the result? What changes if you add axis=1 and the function still returns that Series?
Show answer
With axis=0 the result has row labels "min" and "max" and the original column labels as columns. With axis=1 the function receives rows, and the returned Series index ("min", "max") becomes the column labels, so the result has one row per original row and columns named "min" and "max".