Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Use the Pandas Apply Function to Each Row

Use df.apply(function, axis=1) to run a function on each DataFrame row. Learn what the function receives, how to return results, and when to vectorize instead.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use df.apply(function, axis=1) to call a function once for each row in a pandas DataFrame. By default, the function receives that row as a Series, so you can read values by column name. For simple calculations across columns, a vectorized expression is usually clearer and faster.

Apply a function to each row

Here is a complete example that multiplies each row’s price by its quantity and stores the result in a new column:

As an Amazon Associate I earn from qualifying purchases.

import pandas as pd

df = pd.DataFrame({"price": [10, 20], "quantity": [2, 3]})

def line_total(row):
    return row["price"] * row["quantity"]

df["total"] = df.apply(line_total, axis=1)

The axis=1 argument selects rows. The equivalent spelling is axis="columns". The default, axis=0, applies the function to each column instead. See the pandas.DataFrame.apply API reference.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the function receives and returns

By default, each input is a Series

With the default raw=False, pandas passes the function a Series for each row. Its index contains the DataFrame’s column labels, so access fields by name—for example, row["price"]. This is generally the clearest choice when your logic depends on named columns.

With raw=True, the function instead receives an ndarray. That can suit some NumPy operations, but the input no longer carries column labels; access is positional. Consult the API reference for the behavior and options supported by your installed pandas version.

One scalar per row creates a Series

If the function returns one value for every row, apply returns a Series indexed by the DataFrame’s original row index. That is why the example’s result can be assigned directly to df["total"].

Multiple values per row create multiple columns

To return several named results, return a Series from the function. The returned Series index supplies the output column names:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def summarize(row):
    return pd.Series({
        "total": row["price"] * row["quantity"],
        "is_bulk": row["quantity"] >= 3,
    })

result = df.apply(summarize, axis=1)

Alternatively, a list-like return can be split into columns with result_type="expand". result_type="broadcast" attempts to broadcast returned values while retaining the original columns and shape. These result_type options apply only to row-wise application; see the API documentation for details.

Prefer vectorized operations for straightforward calculations

When an operation can be expressed over whole columns, use pandas or NumPy operations rather than calling a Python function for every row. The example’s total can be calculated directly:

df["total"] = df["price"] * df["quantity"]

Vectorized expressions avoid Python-level per-row function calls and are often more efficient. In its own getting-started guide, pandas compares a user-defined-function example taking 5.6435 seconds with a vectorized version taking 0.0043 seconds. Those are timings for that documentation example, not a general benchmark; results vary with the data, hardware, pandas version and implementation. See Getting started with pandas.

Choose the right approach

  1. Look for an operation over whole columns. Use a pandas or NumPy expression when it naturally describes the calculation.
  2. Use row-wise apply when the logic genuinely needs a row. It is appropriate when several fields must be considered together and no suitable vectorized operation expresses the rule.
  3. Keep label access when names matter. Use the default raw=False for a Series indexed by column labels; consider raw=True only when an ndarray is appropriate.
  4. Measure your actual workload. If performance matters, time representative data and code rather than assuming one method will always be faster.

Do not mutate the row passed to the function

Avoid changing the Series object that pandas passes into your function. The pandas user guide warns that mutating data passed to a user-defined function can cause unexpected behavior or errors and is unsupported. Return the value or values you want instead. See User-Defined Functions (UDFs).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check your pandas version before using JIT engines

The stable DataFrame.apply reference for pandas 3.0.5 documents engine options, including Numba and Bodo decorators, with limitations on type stability and API support. JIT compilation is most suitable when the function itself does substantial work; a fast function may not benefit. Engine interfaces have changed across versions—the pandas 2.2 reference shows an earlier interface—so check the documentation matching your installed version before copying engine-specific syntax. The usual apply(function, axis=1) pattern does not require an engine option.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.