Pandas transform() method is used to perform transformation operations on DataFrame columns or rows.
This method helps apply a function to a subset of data while keeping the shape of the original DataFrame intact. It can be used with lambda functions for more complex transformations.
Unlike .apply(), .transform() cannot produce aggregated results.
The output shape must match the input, making it suitable for element-wise transformations.
Syntax
DataFrame.transform(func, axis=0, *args, **kwargs)
Parameters
Name | Description |
func | Function, It is a function name as string, list of functions, or dictionary. It’s the function to use for transforming the data. |
axis | {0 or ‘index’, 1 or ‘columns’}, default 0. The axis along which the function is applied. |
*args, **kwargs | Additional arguments to pass to the function. |
Return value
It returns a DataFrame with the same shape as the original, with the transformation applied.
Example 1: Basic usage
import pandas as pd
df = pd.DataFrame({'A': range(3), 'B': range(1, 4)})
transformed = df.transform(lambda x: x + 10)
print(transformed)
Output
In this code, we added 10 to every element in the DataFrame.
Example 2: Transforming with a built-in function
import pandas as pd
df = pd.DataFrame({'A': range(3), 'B': range(1, 4)})
transformed = df.transform('sqrt')
print(transformed)
Output
Example 3: Using different functions for columns
import pandas as pd
df = pd.DataFrame({'A': range(3), 'B': range(1, 4)})
transformed = df.transform({'A': lambda x: x * 2, 'B': lambda x: x + 3})
print(transformed)
Output
You can see that we applied different functions to each column.
Example 4: Transforming with groupby
When used with group objects, it allows efficient element-wise transformations within groups.
import pandas as pd
df = pd.DataFrame({'key': ['A', 'B', 'C'] * 2, 'value': range(6)})
grouped = df.groupby('key').transform(lambda x: x - x.mean())
print(grouped)
Output
In this code, we normalized each group’s data by subtracting its mean.
Example 5: Transforming and retaining original structure
import pandas as pd
df = pd.DataFrame({'temp': [37, 38, 39, 36, 37],
'humidity': [80, 85, 88, 75, 90]})
grouped = df[['temp']].transform(lambda x: (x * 9/5) + 32)
print(grouped)
Output
We converted the temperature from Celsius to Fahrenheit while retaining the DataFrame’s structure.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.