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 |
Çhemistry |
Maths |
| Student 1 |
59.488944 |
14.888411 |
52.794760 |
| Student 2 |
21.872113 |
66.481646 |
87.190572 |
| Student 3 |
9.885919 |
54.449674 |
58.696036 |
| Student 4 |
33.804378 |
6.286295 |
30.373699 |
---
Applymap
RoundUpto2Decimal = lambda x: round(x,2)
data.applymap(RoundUpto2Decimal)
|
Physics |
Çhemistry |
Maths |
| Student 1 |
59.49 |
14.89 |
52.79 |
| Student 2 |
21.87 |
66.48 |
87.19 |
| Student 3 |
9.89 |
54.45 |
58.70 |
| Student 4 |
33.80 |
6.29 |
30.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 |
Çhemistry |
Maths |
| Student 1 |
1.000000 |
0.142903 |
0.394620 |
| Student 2 |
0.241642 |
1.000000 |
1.000000 |
| Student 3 |
0.000000 |
0.800118 |
0.498485 |
| Student 4 |
0.482198 |
0.000000 |
0.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{:target="_blank"}