Applying functions over pandas dataframe using apply, applymap and map

  23 Apr 2019
  python

Importing Packages and Datasets

import pandas as pd
import numpy as np
data = pd.DataFrame(np.random.rand(4, 3)*100,
                    columns=['Physics','Çhemistry','Maths'],
                    index = ['Student 1', 'Student 2','Student 3','Student 4'])
data
PhysicsÇhemistryMaths
Student 159.48894414.88841152.794760
Student 221.87211366.48164687.190572
Student 39.88591954.44967458.696036
Student 433.8043786.28629530.373699

Applymap

RoundUpto2Decimal = lambda x: round(x,2)
data.applymap(RoundUpto2Decimal)
PhysicsÇhemistryMaths
Student 159.4914.8952.79
Student 221.8766.4887.19
Student 39.8954.4558.70
Student 433.806.2930.37

Apply

AverageMarks = lambda x: np.mean(x)
data.apply(AverageMarks)
Physics      31.262839
Çhemistry    35.526506
Maths        57.263767
dtype: float64
data.apply(AverageMarks,axis = 1)
Student 1    42.390705
Student 2    58.514777
Student 3    41.010543
Student 4    23.488124
dtype: float64
data.apply(lambda x: (x-np.min(x))/(np.max(x)-np.min(x)))
PhysicsÇhemistryMaths
Student 11.0000000.1429030.394620
Student 20.2416421.0000001.000000
Student 30.0000000.8001180.498485
Student 40.4821980.0000000.000000

Map

SquareOfMarks = lambda x: x**2
data['Physics'].map(SquareOfMarks)
Student 1    3538.934482
Student 2     478.389328
Student 3      97.731389
Student 4    1142.735997
Name: Physics, dtype: float64

Notebook Link - Applying functions over pandas dataframe using apply, applymap and map