How to apply functions element-wise in a dataframe in Python?


It may sometimes be required to apply certain functions along the elements of the dataframe. All the functions can’t be vectorised. This is where the function ‘applymap’ comes into picture.

This takes a single value as input and returns a single value as output.

Example

 Live Demo

import pandas as pd
import numpy as np
my_df = pd.DataFrame(np.random.randn(5,5),columns=['col_1','col_2','col_3', 'col_4', 'col_5'])
print("The dataframe generated is ")
print(my_df)
my_df.applymap(lambda x:x*11.45)
print("Using the applymap function")
print(my_df.apply(np.mean))

Output

The dataframe generated is
    col_1       col_2      col_3      col_4     col_5
0  -0.671510  -0.860741   0.886484   0.842158   2.182341
1  -1.355763   0.247240   -0.653630  -0.278095  0.163044
2  -0.816203   1.664006   1.555648   1.625890   -0.412338
3  -1.013273   -1.565076  1.297014   -0.303504  -1.623573
4  0.725949    -0.077588  -0.886957  0.433478   -0.300151
Using the applymap function
col_1  -0.626160
col_2  -0.118432
col_3  0.439712
col_4  0.463985
col_5  0.001865
dtype: float64

Explanation

  • The required libraries are imported, and given alias names for ease of use.

  • Dataframe is created by using the ‘random’ function and creating data that has 5 rows and 5 columns.

  • The names of the columns are also defined within a list while defining the dataframe values.

  • The dataframe is printed on the console.

  • The ‘applymap’ function is applied on the elements of the dataframe.

  • The function definition is a lambda function written inside the ‘applymap’ function.

  • The data is printed on the console.

Updated on: 10-Dec-2020

931 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements