To Apply our own function or some other library’s function, pandas provide three important functions namely pipe(), apply() and applymap(). These Functions are discussed below.
- Table wise Function Application: pipe()
- Row or Column Wise Function Application: apply()
- Element wise Function Application: applymap()
Table wise Function Application: pipe()
Pipe() function performs the custom operation for the entire dataframe. In below example we will using pipe() Function to add value 2 to the entire dataframe
import pandas as pd import numpy as np import math # own function def adder(adder1,adder2): return adder1+adder2 #Create a Dictionary of series d = {'Score_Math':pd.Series([66,57,75,44,31,67,85,33,42,62,51,47]), 'Score_Science':pd.Series([89,87,67,55,47,72,76,79,44,92,93,69])} df = pd.DataFrame(d) print df print df.pipe(adder,2)
output will be
Original dataframe:
Dataframe with value 2 added:
Row or Column Wise Function Application: apply()
apply() function performs the custom operation for either row wise or column wise . In below example we will be using apply() Function to find the mean of values across rows and mean of values across columns
Create Dataframe
import pandas as pd import numpy as np import math #Create a DataFrame d = {'Score_Math':pd.Series([66,57,75,44,31,67,85,33,42,62,51,47]), 'Score_Science':pd.Series([89,87,67,55,47,72,76,79,44,92,93,69])} df = pd.DataFrame(d) print df
resultant dataframe will be
Row wise Function in python pandas : Apply()
apply() Function to find the mean of values across rows
#row wise mean print df.apply(np.mean,axis=1)
so the output will be
Column wise Function in python pandas : Apply()
apply() Function to find the mean of values across columns
#column wise meanprint df.apply(np.mean,axis=0)
so the output will be
Element wise Function Application in python pandas: applymap()
applymap() Function performs the specified operation for all the elements the dataframe. we will be using the same dataframe to depict example of applymap() Function. We will be multiplying the all the elements of dataframe by 2 as shown below
Example1: applymap() Function in python
import pandas as pd import numpy as np import math # applymap() Function print df.applymap(lambda x:x*2)
so the output will be
Example2: applymap() Function in python
We will be finding the square root of all the elements of dataframe with applymap() function as shown below
import math #applymap() Function to find the sqrt print df.applymap(lambda x:math.sqrt(x))
so the output will be