Pandas DataFrame transform() Method

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

Understanding Pandas DataFrame transform() Method

import pandas as pd

df = pd.DataFrame({'A': range(3), 'B': range(1, 4)})

transformed = df.transform(lambda x: x + 10)

print(transformed)

Output

Output of DataFrame transform() Method

In this code, we added 10 to every element in the DataFrame.

Example 2: Transforming with a built-in function

Figure of 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

Output of transforming with a built-in Function

Example 3: Using different functions for columns

Figure of 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

Output of using different functions for columns

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

Output of transforming with groupby

In this code, we normalized each group’s data by subtracting its mean.

Example 5: Transforming and retaining original structure

Figure of 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

Output of transforming and retaining original structure

We converted the temperature from Celsius to Fahrenheit while retaining the DataFrame’s structure.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.