Free tools Windows power users keep installed
One-click scans. No signup required.
DataFrame.apply() runs a function once for each column or row of a pandas DataFrame. Set axis=0 for one call per column, or axis=1 for one call per row. By default, the function receives a labeled Series; raw=True passes an unlabeled NumPy array instead. The value your function returns—and, for row-wise calls, the optional result_type—determines the result’s shape.
How do I use apply() with a pandas DataFrame?
Import pandas and create a DataFrame, then pass a function to apply(). For example, the official pandas DataFrame.apply API reference demonstrates applying NumPy functions and reductions. This small frame makes the axis behavior easy to see:
import pandas as pd
import numpy as np
df = pd.DataFrame({"A": [4], "B": [9]})
column_roots = df.apply(np.sqrt) # one call per column
row_totals = df.apply(np.sum, axis=1) # one call per row
print(column_roots)
print(row_totals)
With the default axis=0, pandas calls the function separately on column A and column B. With axis=1, it calls the function on the single row containing both values. A named function is often clearer than a longer lambda when the operation has more than one step.
What does axis=1 mean in DataFrame.apply()?
axis=1 means the function is called once for each row. The row is supplied as a Series by default, with the DataFrame’s column names as its index, so the function can select values by label. Conversely, axis=0 (also written 'index') calls the function once per column; that Series is indexed by the DataFrame’s row index. The names refer to the axis being traversed, not the shape of each input: axis=0 does not mean one function call per row.
Recommended Free Tools
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
axis=0or'index': process each column.axis=1or'columns': process each row.
For example, a row-wise function can use column labels directly:
def total_with_bonus(row):
return row["A"] + row["B"] + 1
result = df.apply(total_with_bonus, axis=1)
Does apply() pass a Series or an array?
By default, each function call receives a pandas Series, which preserves labels. Set raw=True to pass an ndarray instead. An array has positional values but no column or index labels, so use integer positions in the function:
def total_from_array(values):
return values[0] + values[1]
result = df.apply(total_from_array, axis=1, raw=True)
The API notes that raw=True can improve performance for NumPy reduction functions. It is appropriate only when the function does not need Series labels; it is not a general speed switch.
Rank #2
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
How does the function’s return value determine the result?
With result_type=None, pandas infers the output from the function’s return value. A scalar returned for each row normally produces a Series indexed by the original rows. If a row function returns a Series, the returned Series’ index labels become output column labels. A list-like return normally remains a Series of list-like values unless you choose an expansion mode. Keep return types consistent across rows or columns: pandas uses the first computed result to infer how to assemble the output.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Scalar return: one result per row
row_totals = df.apply(np.sum, axis=1)
Each row produces one number, so the result is a Series with the original row index.
List-like return: keep or expand values
A function that returns a list for each row normally yields a Series containing lists. Set result_type='expand' to put those values into separate columns:
Rank #3
- ALL-EXPANSIVE VIEW: The three-sided borderless display brings a clean and modern aesthetic to any working environment; In a multi-monitor setup, the displays line up seamlessly for a virtually gapless view without distractions
- SYNCHRONIZED ACTION: AMD FreeSync keeps your monitor and graphics card refresh rate in sync to reduce image tearing; Watch movies and play games without any interruptions; Even fast scenes look seamless and smooth.
- SEAMLESS, SMOOTH VISUALS: The 75Hz refresh rate ensures every frame on screen moves smoothly for fluid scenes without lag; Whether finalizing a work presentation, watching a video or playing a game, content is projected without any ghosting effect
- MORE GAMING POWER: Optimized game settings instantly give you the edge; View games with vivid color and greater image contrast to spot enemies hiding in the dark; Game Mode adjusts any game to fill your screen with every detail in view
- SUPERIOR EYE CARE: Advanced eye comfort technology reduces eye strain for less strenuous extended computing; Flicker Free technology continuously removes tiring and irritating screen flicker, while Eye Saver Mode minimizes emitted blue light
def values_and_total(row):
return [row["A"], row["B"], row["A"] + row["B"]]
expanded = df.apply(values_and_total, axis=1, result_type="expand")
Use result_type='reduce' to ask pandas for a Series where possible instead of expanding list-like results. Use result_type='broadcast' when the function’s results should be broadcast along the applied axis while retaining the original DataFrame’s labels and shape; the returned values must be compatible with that shape. These result_type options apply only with axis=1.
Series return: choose output column labels
For a row-wise call, returning a Series lets the function define output labels as well as values:
def labeled_result(row):
return pd.Series({
"total": row["A"] + row["B"],
"difference": row["B"] - row["A"],
})
summary = df.apply(labeled_result, axis=1)
The returned Series index—total and difference here—becomes the result’s columns.
Rank #4
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
How do apply() arguments work?
Pass additional positional arguments as a tuple through args, and pass named options directly as keyword arguments. For instance:
def add_offset(row, offset):
return row["A"] + row["B"] + offset
result = df.apply(add_offset, axis=1, args=(10,))
Here, pandas supplies each row first and then passes 10 as offset. The current stable API signature also includes by_row; it was added in pandas 2.1.0. It governs compatibility behavior for certain callable forms and is usually unnecessary for straightforward DataFrame examples. Do not confuse DataFrame.apply() with Series.apply(), which has its own behavior for applying functions to Series values or to the Series itself.
When should I use apply() instead of map(), agg(), or transform()?
Choose the method that matches the operation’s unit and output contract. A direct vectorized operation or specialized method is often the clearest option for arithmetic and common reductions; a custom Python callback may add overhead.
Best Value
- Incredible Images: The Acer KB272 G0bi 27" monitor with 1920 x 1080 Full HD resolution in a 16:9 aspect ratio presents stunning, high-quality images with excellent detail.
- Adaptive-Sync Support: Get fast refresh rates thanks to the Adaptive-Sync Support (FreeSync Compatible) product that matches the refresh rate of your monitor with your graphics card. The result is a smooth, tear-free experience in gaming and video playback applications.
- Responsive!!: Fast response time of 1ms enhances the experience. No matter the fast-moving action or any dramatic transitions will be all rendered smoothly without the annoying effects of smearing or ghosting. A 120Hz refresh rate speeds up the frames per second to deliver smooth 2D motion scenes in gaming and video.
- 27" Full HD (1920 x 1080) Widescreen IPS Monitor | Adaptive-Sync Support (FreeSync Compatible)
- Refresh Rate: Up to 120Hz | Response Time: 1ms VRB | Brightness: 250 nits | Pixel Pitch: 0.311mm
| Method | Typical unit of work | Typical output intent |
|---|---|---|
DataFrame.apply() |
A whole row or column per function call | Depends on what the function returns; row-wise result_type can guide assembly |
DataFrame.map() |
Individual DataFrame elements | Elementwise result |
DataFrame.aggregate() or agg() |
Aggregation functions | Summarized values |
DataFrame.transform() |
Column- or group-oriented transformation | Transformed values that preserve the input shape |
Use apply() when the calculation naturally needs a complete row or column, particularly when a row function benefits from labeled Series access. For element-by-element work, pandas points to DataFrame.map(); for aggregation, use agg() when it expresses the calculation; for shape-preserving transformations, consider transform(). Direct pandas or NumPy operations are preferable when they describe the calculation without a custom callback.
Is DataFrame.apply() slow, and should I use a JIT engine?
There is no universal speed figure for apply(). The pandas performance guide explains that compilation adds overhead, especially for small inputs, while later cached calls can help on sufficiently large workloads. Its illustrative timings depend on the guide’s example data, code, software, and environment; they are not a guaranteed speedup for another DataFrame.
Start by checking whether vectorized pandas or NumPy operations can express the calculation. If considering JIT compilation, benchmark a representative workload and include compilation cost when the program runs only once. Type-stable functions are generally important for the documented JIT options, and supported operations vary.
The current stable API reference identifies itself as pandas 3.0.6 and documents an engine interface that accepts JIT decorators such as numba.jit, numba.njit, or bodo.jit. It also says string engine parameters are planned to stop being supported in a future pandas version. The pandas 2.2 API instead documents the older 'python' and 'numba' engine strings and cautions that its Numba path should be used with raw=True because of Numba/pandas limitations. These interfaces differ; check the documentation for your installed pandas version before copying engine code. The engine parameter was added in pandas 2.2.0.
Quick Recap
What should I avoid when writing an apply() function?
- Mutating the input Series: pandas states, “Functions that mutate the passed object can produce unexpected behavior or errors and are not supported.” Return computed values instead of changing the Series supplied to the function.
- Assuming labels are always present: labels are available with the default Series input, but not with
raw=True. - Mixing incompatible return types: pandas infers output assembly from the first computed result, so return a consistent kind of value for each row or column.
- Misreading the axis:
axis=0means one call per column;axis=1means one call per row. - Copying engine examples across versions: the documented engine interfaces have changed, so use the reference matching your installed pandas release.
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.

