Pandas DataFrame applymap() Method

In this tutorial, we will learn the python pandas DataFrame.applymap() method. This method applies a specified function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame.

This function is similar to the DataFrame.apply() method, the only difference is that DataFrame.apply() takes the whole column as a parameter and then assigns the result to this column and DataFrame.applymap() takes the separate cell value as a parameter, and assigns the result back to this cell.

The below shows the syntax of DataFrame.applymap() method.

Syntax

DataFrame.applymap(func, na_action=None)

Parameters

func: It represents the function that is callable. The function returns a single value from a single value.

na_action: It represents the None or ‘ignore’ but the default value is None. If it is ‘ignore’, propagate NaN values, without passing them to func.

Example 1: Applying the DataFrame.applymap() Method on the dataframe

The below example shows how the DataFrame.applymap() method works and in this example, the method returns the number of characters present in all the cells.

df = pd.DataFrame([[1.23, 2.23], [3.3, 4]],columns=['A','B'])
print("-----DataFrame-----")
print(df)
print(df.applymap(lambda x: len(str(x))))

Once we run the program we will get the following output.


-----DataFrame-----
A B
0 1.23 2.23
1 3.30 4.00
A B
0 4 4
1 3 3

Example 2: Applying the DataFrame.applymap() method on the dataframe

The below shows another example of DataFrame.applymap() method. In this example, add value to the elements of the cell of the DataFrame and print the output.

df = pd.DataFrame([[1.23, 2.23], [3.3, 4]],columns=['A','B'])
print("----------Adding element to the DataFrame--------")
print(df.applymap(lambda x: x+1))

Once we run the program we will get the following output.


----------Adding an element to the DataFrame--------
A B
0 2.23 3.23
1 4.30 5.00

Example 3: Applying the DataFrame.applymap() Method

In the below example, we are passing np.sum function as a parameter to the DataFrame.applymap() method.

import pandas as pd
import numpy as np
df=pd.DataFrame([[10,11,12],[20,21,22]],columns=['A','B','C'])
print("Applying sum function to all the elements of DataFrame")
print(df.applymap(np.sum))

Once we run the program we will get the following output.


Applying sum function to all the elements of DataFrame
A B C
0 10 11 12
1 20 21 22

Conclusion

In this tutorial, we learned the python pandas DataFrame.applymap() method. This function is similar to the DataFrame.apply() method. We solved examples by applying this method on the DataFrame and understood how it takes the cell values as a parameter and assigns the result back to this cell.