Pandas DataFrame Applymap Method

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn how to use the applymap() method in Pandas DataFrame. The applymap() method applies a specified function to each element in a DataFrame, producing a new DataFrame with the transformed values.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Create a DataFrame

First, let's create a DataFrame called df with some example data. This DataFrame will have two columns, 'A' and 'B', and two rows.

import pandas as pd

df = pd.DataFrame([[1.23, 2.23], [3.3, 4]], columns=['A','B'])
print("-----DataFrame-----")
print(df)

Apply a Function to Each Element

Next, we will apply a function to each element of the DataFrame using the applymap() method. In this example, we will use a lambda function to calculate the length of each value in the DataFrame.

print(df.applymap(lambda x: len(str(x))))

Add Values to Each Element

Now, let's apply a different function to add a value to each element of the DataFrame. We will add 1 to each element using the applymap() method.

print(df.applymap(lambda x: x + 1))

Apply a Built-in Function

In this step, we will use a built-in function from the NumPy library as the input for the applymap() method. We will pass the np.sum function to the applymap() method to calculate the sum of each element.

import numpy as np

df = pd.DataFrame([[10,11,12],[20,21,22]],columns=['A','B','C'])
print(df.applymap(np.sum))

Summary

In this lab, we have learned how to use the applymap() method in Pandas DataFrame. We have seen how to apply a function to each element, add values to each element, and apply a built-in function using the applymap() method. This method provides a flexible way to transform the values in a DataFrame elementwise.

Other Python Tutorials you may like