Sub topic 8
DataFrame.apply across columns and rows
This chapter assumes you can write Python functions and lambdas, build a DataFrame, and select or assign columns. It also assumes you have seen Series.apply. Here you will see what DataFrame.apply passes to your function and how the axis argument changes that.
What apply passes to your function
Series.apply hands your function one value at a time. DataFrame.apply hands it a whole one-dimensional slice, as a Series. Which slice depends on axis:
axis=0(the default) passes each column. The function works down the rows.axis=1passes each row. The function works across the columns.
The names are easy to mix up. Read axis as the direction the function travels through the data, not as the thing you get.
Row-wise logic with axis=1
Use axis=1 when a result depends on 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) price qty total
0 10.0 1 10.0
1 20.0 2 40.0
2 30.0 3 90.0The function receives row as a Series. Its index holds the column names, so row["price"] selects a value by column label. The function returns one number per row, so apply returns a Series, which you assign to a new column.
This version works, but it calls Python code once per row. For simple arithmetic like this, df["price"] * df["qty"] gives the same result and is much faster. A later chapter covers vectorized alternatives. Keep row-wise apply for logic that is hard to write as column arithmetic, such as branching on several fields.
Column-wise logic with axis=0
With the default axis=0, the function receives each column. This suits summaries, because methods like col.min() work on a whole 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) a b
min 1 4
max 3 6The function returns a Series for each column. apply uses the index of each returned Series as the row labels of the result and the original column names as its columns. If the function returned a single number per column, you would get a Series indexed by column name instead. The chapter on return shapes covers these cases in full.
Gotchas with row slices
A row is one Series, so it has a single dtype. When columns differ in type, pandas picks a common one for the row.
- Integer and float columns give a float row. An integer such as
qtyis seen as1.0inside the function. - A string column mixed with numbers gives an
objectrow, and the numbers stay as Python or NumPy scalars.
This matters when the function checks types or formats values. If you only need two numeric columns, select them first, as in df[["price", "qty"]].apply(..., axis=1). That keeps the row numeric and avoids passing data the function does not use.
Two more points:
- Your function must handle every row or column. An error on one slice stops the whole call, and the traceback does not always say which row failed.
- Do not change the DataFrame inside the function. Return new values and assign the result afterward.
Choosing the axis
| Goal | Axis | The function receives |
|---|---|---|
| Combine several columns into one value per row | `axis=1` | A row Series |
| Summarize or transform each column | `axis=0` | A column Series |
| Change every cell independently | Use `DataFrame.map` | A single value |
Exercise
A DataFrame has numeric columns "width" and "height". You write df.apply(lambda row: row["width"] * row["height"]) and get a KeyError. What is wrong, and what is the fix?
Show answer
The default axis=0 passes each column, so the lambda gets a column Series whose index is the row labels. Looking up "width" in that index raises KeyError. Pass axis=1 so each row arrives with the column names as its index: df.apply(lambda row: row["width"] row["height"], axis=1). The vectorized form df["width"] df["height"] is shorter and faster.