Function Application Continued(applymap)...

Applymap - Apply a function to a Dataframe element wise. This method applies a function that accepts and returns a scalar to every element of a DataFrame.
Example:-
import pandas as pd
import numpy as np
df=pd.DataFrame([[1, 2.12], [3.356, 4.567]])
print(df.applymap(lambda x : len(str(x))))
Output:-
     0   1
0  3    4
1  5    5
Explanation:-
  • applymap applies particular function to each element of the dataframe.
  • lambda operator is used to create functions without a name.
  • x represent each element of dataframe and len(str(x)) is the operation applied on elements
  • str function is used to convert integer into string
  • len is a function used to calculate the length of the string
Quiz:-
1. import pandas as pd
import numpy as np
df=pd.DataFrame([[1, 2.12], [3.356, 4.567]])print(df.applymap(lambda x: x**2))
#Post your answer in comment

2. import pandas as pd
import numpy as np
def ff(x):
    if x>4:
       x=x*2
       return x
    else:
       return x
df=pd.DataFrame([[1, 2], [3, 4]])
print(df.applymap(lambda x: ff(x)))
#Post your answer in comment

Comments

Popular posts from this blog

Python Tokens

Python Tokens - Operators

Descriptive Statistics - count & sum