Column-wise transformation
Apply the same elementwise or column-compatible operation to every column while retaining the original rows and columns.
Pandas · Module
DataFrame.transform applies a function along columns or rows and returns transformed data while preserving the DataFrame’s axis shape. It supports callables, function names, lists, and label-based mappings.
DataFrame.transform applies a function along columns or rows and returns transformed data without changing the required axis length. It accepts a callable, function name, collection of functions, or label-to-function mapping, and forwards extra positional and keyword arguments to the function.
DataFrame.transform(func, axis=0, *args, **kwargs)| Name | Type | Description |
|---|---|---|
func | function, str, list-like or dict-like | Function used to transform the data; it can be callable, a string, list-like, or dict-like. |
axis | {0 or 'index', 1 or 'columns'}, default 0 | Transformation direction: 0 or 'index' applies to columns; 1 or 'columns' applies to rows. Defaults to 0. |
*args | tuple | Additional positional arguments passed to func. |
**kwargs | dict | Additional keyword arguments passed to func. |
DataFrame with the same length as self.
import pandas as pd
values = pd.DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]})
result = values.transform(lambda column: column + 1)
print(result)Adds one to every column while preserving the DataFrame's shape.
Apply the same elementwise or column-compatible operation to every column while retaining the original rows and columns.
Run a row-oriented callable when each row should be processed as a unit.
Select different transformations for different labeled columns.
transform applies a function while requiring the output to retain the input's axis shape. Unlike an aggregation, it produces DataFrame-shaped transformed data rather than reducing it.
Follow-up: How does transform react to a shape-changing function? It raises ValueError when the returned DataFrame has a different length than the original.
The default axis is 0, meaning the function is applied to each column. With axis=1 or axis='columns', it is applied to each row.
Follow-up: What validation still applies with axis=1? The function's result must preserve the required length along that transformation axis.
func may be a callable, string function name, list-like collection, or dict-like mapping from axis labels to functions. For a dict-like input, each label can select one function or a list of functions.
Follow-up: What happens if func is both list-like and dict-like? Dict-like behavior takes precedence.
pandas.DataFrame.applypandas.Series.transform