Pandas DataFrame transform() method with examples

Spread the love

The transform() method in pandas allows you to execute a function for each value of the DataFrame.

Syntax –

DataFrame.transform(func, axis=0, *args, **kwargs)

func – Function to use for transforming the data.

axis – If 0 or ‘index’: apply function to each column. If 1 or ‘columns’: apply function to each row.

*args – Positional arguments to pass to func.

**kwargs – Keyword arguments to pass to func.

Examples –

1 . Create a DataFrame –

Let’s create a dataframe to work with.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[1, 2, 3],
                  'B':[4, 5, 6],
                  'C':[7, 8, 9]})
df

2 . Apply a function to a dataframe –

Let’s say we want to add 10 to each values in the dataframe. For this we can use the transform() method in pandas.

df.transform(lambda x: x + 10)

3 . Apply a function to a series –

We can also apply a function to each values in a series.

# create a series
s = df['A']

# apply functions to the series
s.transform(['sqrt','exp'])

Rating: 1 out of 5.

Leave a Reply