Apply function to column and row in the Dataframe
Here. we will see how to apply a function to more than one row and column using df.apply() method.
For Column
Here, we applied the function to the x, and y columns.
Python3
# import pandas and numpy library import pandas as pd import numpy as np # List of Tuples matrix = [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] # Create a DataFrame object df = pd.DataFrame(matrix, columns = list ( 'xyz' ), index = list ( 'abc' )) # Apply function numpy.square() # for square the values of # two columns 'x' and 'y' new_df = df. apply ( lambda x: np.square(x) if x.name in [ 'x' , 'y' ] else x) # Output print (new_df) |
Output:
x y z
a 1 4 3
b 16 25 6
c 49 64 9
For Row
Here, we applied the function to the b, and c rows.
Python3
# import pandas and numpy library import pandas as pd import numpy as np # List of Tuples matrix = [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )] # Create a DataFrame object df = pd.DataFrame(matrix, columns = list ( 'xyz' ), index = list ( 'abc' )) # Apply function numpy.square() to # square the values of two rows # 'b' and 'c' new_df = df. apply ( lambda x: np.square(x) if x.name in [ 'b' , 'c' ] else x, axis = 1 ) # Output print (new_df) |
Output:
x y z
a 1 2 3
b 16 25 36
c 49 64 81
Apply a function to single or selected columns or rows in Pandas Dataframe
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function.