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.

Syntax: Dataframe/series.apply(func, convert_dtype=True, args=())

Parameters: This method will take following parameters :
func: It takes a function and applies it to all values of pandas series.
convert_dtype: Convert dtype as per the function’s operation.
args=(): Additional arguments to pass to function instead of series.

Return Type: Pandas Series after applied function/operation.

Method 1: Using Dataframe.apply() and lambda function.
Example 1: For Column



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 lambda
# to find the squares of the values of 
# column whose column name is 'z'
new_df = df.apply(lambda x: np.square(x) if x.name == 'z' else x)
  
# Output
new_df

chevron_right


Output :
dataframe

Example 2: For Row.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 lambda 
# to find the squares of the values of row
# whose row index is 'b'
new_df = df.apply(lambda x: np.square(x) if x.name == 'b' else x, 
                axis = 1)
  
# Output
new_df

chevron_right


Output :
dataframe-2

Method 2: Using Dataframe/series.apply() & [ ] Operator.

Example 1: For Column.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 a function to one column 'z'
# and assign it back to the same column 
df['z'] = df['z'].apply(np.square)
  
# Output
df

chevron_right


Output :
dataframe

Example 2: For Row.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 a function to one row 'b' 
# and assign it back to the same row 
df.loc['b'] = df.loc['b'].apply(np.square)
  
# Output
df

chevron_right


Output :
dataframe-2



Method 3: Using numpy.square() method and [ ] operator.
Example 1: For Column

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 a function to one column 'z' and 
# assign it back to the same column 
df['z'] = np.square(df['z'])
  
# Output
print(df)

chevron_right


Output :
dataframe

Example 2: For Row.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 a function to one row 'b' and 
# assign it back to the same row
df.loc['b'] = np.square(df.loc['b'])
  
# Output
df

chevron_right


Output :
dataframe-2

We can also apply a function to more than one column or row in the dataframe.

Example 1: For Column

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
new_df

chevron_right


Output :
dataframe-2

Example 2: For Row.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
new_df

chevron_right


Output :
dataframe-1




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.