There are many functions in pandas that allow you to perform an elementwise operation. And applymap in pandas is one of them. In this entire tutorial, You will know how to use applymap method in pandas. But before going to the coding part let’s learn the syntax of this method.
The applymap pandas function Syntax
Here you can see there is only one parameter available and it is the func. This method accepts only a function parameter. It returns the transformed pandas dataframe. In this post, I will show you various examples.
Sample DataFrame Creation
Here, I will create a sample data frame to implement the method. The dataframe will be time-series data and it has three columns. Just Run the following lines of code to create the dataframe.
import numpy as np import pandas as pd import datetime todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') columns = ['A','B', 'C'] data = np.array([np.arange(10)]*3).T df = pd.DataFrame(data,index=index, columns=columns)
Examples of applymap() method in pandas
Example 1: Use of custom function
In this example Firstly, I will define a function that will multiply each column of the dataframe with 10.
def add(values): return values*10
Lastly, just pass the custom function as an argument inside the applymap() method. It will do element-wise multiplication in each column.
Example 2: applymap in pandas implementation using lambda
In this example, I will directly pass the lambda function as an argument of apllymap(). It will take each element of the values and multiply with 10.
Execute the below lines of code.
df.applymap(lambda x : x*10)
You can see in both examples output is the same. But which example is fast. If you use the time comparison on both the execution of the function. Then the first example is fast compared to the second method. So choose the first method.
Difference between map() and applymap() method
A lot of readers have asked me to tell the difference between the map() and applymap() method. The answer is simple. The map() function works on specific rows or columns. But applymap() method do elementwise operation on the entire dataframe.
These are the examples I have implemented for you. Hope it helps you in understanding the use of the applymap() pandas method. Even if you have any query then you can contact us to get more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.