Knowledge base / Python

pandas apply: rows, columns and the shape of the result

Three orders show what a function receives and what apply returns. I separate working with an entire row from transforming individual cells.

Kajo RudzińskiPublished Updated 6 min read

A complete row lifts from a data grid beside a column and a tray of separate cells in pixel art.

Before using apply, I ask what my function should receive: one value, a whole column or a whole row. That makes it easier to choose a method and understand the output shape. Using the name apply on a Series and a DataFrame does not automatically imply identical input behaviour. Confusing the two can cause a failure before the first useful calculation happens.

The examples below follow the pandas 3.1 documentation and use synthetic numbers. Three orders are enough to trace each decision without random data or performance guesses based on code length. The aim is a clear input contract and a predictable return value from the function, rather than treating apply as a compulsory part of every transformation.

One shared table for the examples

Each row represents an order. The ordered column contains requested quantities, and delivered contains completed quantities. In this exercise, they are nonnegative integers and delivery never exceeds the order.

import pandas as pd

orders = pd.DataFrame(
    {"ordered": [3, 5, 4], "delivered": [3, 2, 0]},
    index=["A", "B", "C"],
)

A is complete, B partially delivered and C still waiting. I keep the same table throughout the entry. New results go into separate variables, so a later fragment does not depend on an accidental structural change made by an earlier example. That is a straightforward way to make learning material easier to follow and individual results easier to relate to their source.

DataFrame.apply with axis=0 receives a column

DataFrame.apply defaults to axis=0 and raw=False. With the single Python function used here, this passes each complete column as a Series.

column_totals = orders.apply(lambda column: column.sum(), axis=0)

The first Series contains 3, 5 and 4, totalling 12. The second contains 3, 2 and 0, totalling 5. The result has ordered and delivered labels. The function receives a column, even if axis zero initially makes you think of a row number. I remember the object passed to the function rather than guessing the direction from the parameter’s name.

For an ordinary total, I would simply choose orders.sum(). The lambda demonstrates the mechanism but adds an unnecessary step to the final solution. First look for an existing method that describes the task. Apply is useful when I genuinely need to supply custom logic. It does not need to sit between every input and every standard operation on that input.

axis=1 passes an entire row

Now I want the remaining quantity for each order. A row contains both necessary columns. With raw=False, their labels are available inside the function.

remaining = orders.apply(
    lambda row: row["ordered"] - row["delivered"],
    axis=1,
)

The result is A: 0, B: 3 and C: 4. One scalar is returned for each row, so the result is a Series indexed by order. For this simple subtraction, however, I would choose orders[“ordered”] - orders[“delivered”] directly. It expresses the operation on columns without calling my own function separately for each row.

I would avoid promising a particular time improvement without measurement on suitable data. The pandas performance guide encourages using available operations before further optimisation. Replacing a loop with apply does not, by itself, make the calculation vectorised. The behaviour and number of calls made by the supplied function still matter, as does the work performed inside each call.

A custom function can use several fields

For a readable status rule, I use a named function. A missing quantity produces a separate state rather than silently becoming zero. Known quantities follow the assumptions of this exercise.

def delivery_status(row):
    if pd.isna(row["ordered"]) or pd.isna(row["delivered"]):
        return "unknown"
    if row["delivered"] == row["ordered"]:
        return "complete"
    if row["delivered"] == 0:
        return "waiting"
    return "partial"

statuses = orders.apply(delivery_status, axis=1)

A receives complete, B partial and C waiting. This is an explicit rule for our table, rather than a full order management model. Returns, overdeliveries or negative adjustments would require additional conditions. I would check those assumptions before putting the status into an operational report. A short function can still depend on a substantial agreement about what its fields are allowed to contain.

The function returns a value instead of modifying the supplied row. The reference warns that mutating passed objects is unsupported and may produce errors or unexpected behaviour. Assign the finished result to a destination table afterwards. This makes it easier to identify which part calculates the value and which part changes the data structure used by the rest of the project.

One mechanism accepts a complete row strip while another processes separate cells.

Multiple values with result_type=expand

When a function returns a list, decide whether you want a list stored in one cell or separate output columns. This example uses DataFrame.apply with axis=1, and result_type=“expand” expands two returned values.

parts = orders.apply(
    lambda row: [
        row["delivered"],
        row["ordered"] - row["delivered"],
    ],
    axis=1,
    result_type="expand",
)
parts.columns = ["done", "remaining"]

The parts rows are A: 3 and 0, B: 2 and 3, and C: 0 and 4. The index still identifies the orders. Each call returns the same structure and length. I would avoid a function that sometimes returns a number, sometimes a list and sometimes a dictionary. A reader then has little basis for knowing which structure the next step should expect.

In this basic pattern, result_type=“expand” describes the return from a function applied to DataFrame rows. I would avoid adding it to Series.apply and expecting identical behaviour. These are separate APIs. An additional Series.apply argument can be forwarded to the user’s function, so a similar method name is insufficient reason to transfer parameters between the two calls.

Series.apply and map have their own uses

Series.apply, with a simple Python callable and the default by_row=“compat”, passes successive Series values. For example, orders[“ordered”].apply(lambda value: value * 2) gives 6, 10 and 8 against A, B and C. The function receives a quantity here, rather than an entire order with both fields available.

Series.map is useful for mapping a column, including through a dictionary. DataFrame.map transforms individual cells across a frame. I choose that method when a function accepts and returns one scalar. It cannot replace a rule needing to compare several fields of the same row, because those fields are no longer passed together.

DataFrame.map appeared in pandas 2.1 when applymap was deprecated. Pandas 3.0 removed DataFrame.applymap. The claim that map works only on Series is therefore outdated. For old code, I would establish the library version and the receiving object before choosing a replacement. The historical name alone does not describe the whole migration decision.

What I would check before using it

I retained raw=False because the functions use column labels. Setting raw=True passes NumPy arrays instead of Series and needs a different access pattern. I would avoid switching it on casually in a function using row[“ordered”]. Changing the input object changes the function’s contract, even when the variable keeps the same name and the call looks almost identical.

Agree missing-value behaviour and permitted types first. Our status rule returns unknown for a missing input, while simple subtraction can preserve a missing value. These are deliberate choices. Apply does not decide whether an absent delivery quantity means zero delivered items or no information. That distinction belongs to the source and the reporting definition, and it needs an explanation before the result is used.

Finally, sketch the expected output: row count, labels and the number of returned values per order. Add an unknown delivered quantity and explain the resulting status. If you only need column summaries, see pandas agg. The method should follow from the required result and the object passed into the function. That is a more reliable starting point than choosing apply because it appears flexible.

Key takeaways

Which axis means rows in DataFrame.apply?

axis=1 passes rows to the function, while the default axis=0 passes columns. With raw=False, each object is a Series carrying the appropriate labels.

Is apply always faster than a loop?

There is no such guarantee. Calling a Python function for successive rows has overhead. For simple work, consider a direct column operation or a built-in method first, without claiming an unmeasured speedup.

What replaces applymap?

DataFrame.map, available since pandas 2.1, applies a scalar-to-scalar function to individual cells. DataFrame.applymap was removed in pandas 3.0. Series also has its own map method.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.