Saturday, May 4, 2019

XII-IP : Transform, applymap and apply in Pandas

Transform

Takes one function that is expected to be applied to a column and return a column of equal size. Pandas DataFrame.transform() function call func on self producing a DataFrame with transformed values and that has the same axis length as self.
import pandas as pd
d1 = {'rollno':[101,101,103,102,104], 'maths': [80,70,80,60,70],\
      'physics':[90,40,50,90,65],'chem':[75,80,60,85,60] }
df = pd.DataFrame(d1)
display(df)
r = df.transform(func=lambda x:x+10)
print('--------------Transform----------------')
display(r)

  rollno maths physics chem
0 101 80 90 75
1 101 70 40 80
2 103 80 50 60
3 102 60 90 85
4 104 70 65 60
--------------Transform----------------
  rollno maths physics chem
0 111 90 100 85
1 111 80 50 90
2 113 90 60 70
3 112 70 100 95
4 114 80 75 70


Applymap

This takes a function and returns a new dataframe with the results of that function being applied to the value in each cell and replacing the value of the cell with the result.

import numpy as np
s = df.applymap(np.sqrt)
print('--------------applymap----------------')
display(s)

--------------applymap----------------
  rollno     maths    physics    chem
0 10.049876 8.944272 9.486833 8.660254
1 10.049876 8.366600 6.324555 8.944272
2 10.148892 8.944272 7.071068 7.745967
3 10.099505 7.745967 9.486833 9.219544
4 10.198039 8.366600 8.062258 7.745967

Apply

Takes a function and applies it either row-wise or column-wise depending on the value of axis parameter. Apply may give the same result as transfom() or applymap() with parameter set to non-aggregate function.

print('----------apply behaving as applymap-----------')
x = df.apply(np.sqrt)
display(x)
print('----------apply with axis =0-----------')
t = df.apply(np.mean)
display(t)
print('----------apply with axis =1-----------')
t = df.apply(np.mean, axis=1)
display(t)
output:

----------apply behaving as applymap-----------
     rollno maths     physics chem
0 10.049876 8.944272 9.486833 8.660254
1 10.049876 8.366600 6.324555 8.944272
2 10.148892 8.944272 7.071068 7.745967
3 10.099505 7.745967 9.486833 9.219544
4 10.198039 8.366600 8.062258 7.745967
----------apply with axis =0-----------
rollno     102.2
maths       72.0
physics     67.0
chem        72.0
dtype: float64
----------apply with axis =1-----------
0    86.50
1    72.75
2    73.25
3    84.25
4    74.75
dtype: float64

Another example of applymap and transform
d=df.transform(func=lambda x:x+10)
display(d)
e=df.applymap(lambda x:x+10)
display(e)

output:
  rollno maths physics chem
0 111 90 100 85
1 111 80 50 90
2 113 90 60 70
3 112 70 100 95
4 114 80 75 70
  rollno maths physics chem
0 111 90 100 85
1 111 80 50 90
2 113 90 60 70
3 112 70 100 95
4 114 80 75 70

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.