How to use the Series.transform() function in pandas
Overview
The pandas Series.transform() function applies a function on itself and produces a Series of the transformed element with the same axis shape as itself.
Syntax
Series.transform(func, axis=0)
Parameters:
func: This represents the function or list of functions used to transform the series elements.axis: This represents the parameter needed forDataFramecompatibility. It can be0or index.
Code example
The following code will demonstrate how to use the Series.transform() function in pandas:
import pandas as pd# create Seriesmy_series = pd.Series([17, 10, 28, 15, 23, 7, 9, 36, 14])# apply lambda function to series element# using product()print(my_series.transform(lambda x: x **2 - 100))print(len(my_series))
Code explanation
In the code above:
-
Line 1: We import the
pandaslibrary. -
Lines 4: We create Series called
my_seriesof length9. -
Line 8: We pass a
lambdafunction as an argument to thetransform(), which multiplies each element in theSeriesby the power of2and subtracts100from each.