Exception Handling in Pandas .apply() Function

Learn, how to use exception handling in pandas .apply() function in Python?
Submitted by Pranit Sharma, on December 05, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

In programming, exception handling refers to the methods and techniques that are used to catch and solve any exception while running the program.

In Python, we use to try and except keywords for the purpose of exception handling, at first, the control will go to try and if any exception occurs it will go inside the except which will tell the programmer about the details of the exception that occurred.

Exception Handling in Pandas using the .apply() Method

The apply() method clearly passes the columns of each group in the form of a DataFrame inside the function which is described in the apply() method. The function described inside the apply() method returns a series or DataFrame (NumPy array or even a list).

To use exception handling in apply() method first we need to define another function where we can write our code for exception handling and then we will call this function using a lambda function inside the apply function.

Let us understand with the help of an example,

Python program to use exception handling in pandas .apply() function

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame(np.array([['Foo','Foo'], [1,2]]))

# Display Original df
print("Original DataFrame:\n",df,"\n")

# Defining a function
def fun(x):
        return int(x) + 1
        return 'error:' + str(x)

# Using apply method
res = df[0].apply(lambda x: fun(x))

# Display result


The output of the above program is:

Example: Exception Handling in Pandas .apply() Function

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.