Python | Pandas DataFrame.transform

Python Methods and Functions

DataFrame.transform() Pandas DataFrame.transform() calls func on self creating the DataFrame with converted values, whose axis length is the same as self.

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

Parameter:
func: Function to use for transforming the data
axis: {0 or ' index ', 1 or' columns'}, default 0
* args: Positional arguments to pass to func.
** kwargs: Keyword arguments to pass to func.

Returns: DataFrame

Example # 1: Use DataFrame. transform () to add 10 to each element in the data frame.

# import pandas as pd

import pandas as pd

 
# Create DataFrame

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , None , 1 ], 

"B" : [ 7 , 2 , 54 , 3 , None ], 

"C " : [ 20 , 16 , 11 , 3 , 8 ], 

"D" : [ 14 , 3 , None , 2 , 6 ]}) 

  
# Create index

index_ = < / code> [ 'Row_1' , ' Row_2' , 'Row_3' , 'Row_4' , ' Row_5' ]

 
# Set index

df.index = index_

 
# Print DataFrame

print (df)

Output:

Now we will use the DataFrame .transform () to add 10 to each home to the data frame element.

# add 10 to each element of the data frame

result = df.transform (func = lambda x: x + 10 )

 
# Print result

print (result)

Output:

As we can see in the output, DataFrame.transform () has successfully added 10 to each element of this Dataframe.

Example # 2: Use DataFrame.transform () to find the square root and result of Euler's number raised to each element of the data frame.

# import pandas as pd

import pandas as pd

 
# Create DataFrame

df = pd.DataFrame ({ " A " : [ 12 , 4 , 5 , None , 1 ], 

  " B " : [ 7 , 2 , 54 , 3 , None ], 

"C" : [ 20 , 16 , 11 , 3 , 8 ], 

"D" : [ 14 , 3 , None , 2 , 6 ]}) 

  
# Create index

index_ = [ ' Row_1' , 'Row_2' , 'Row_3' , 'Row_4' , ' Row_5' ]

 
# Set index

df.index = index_

  
# Print DataFrame

< p> print (df)

Output:

We will now use DataFrame.transform () to find the square root and result of the Euler number raised to each element of the data frame.

# pass a list of functions

result = df.transform (func = [ 'sqrt' , 'exp' ])

 
# Print result

print (result)

Output:

As we can see in the output, DataFrame. transform () successfully performed the desired operation on the given data frame.





Tutorials