Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch a pandas DataError?

I have since fixed the bug that caused the DataError, but I can not for the life of me figure out how to catch it explicitly:

try:
    df["my column"] = df.baddata + df.morebaddata
except DataError:
   print "Caught Error!"

Gives: NameError: name 'DataError' is not defined

Then I tried pd.core.frame.DataError and received an AttributeError. I also tried Googling this but could not find a list of pandas error types. What is the correct path for DataError?

like image 641
A User Avatar asked Apr 07 '15 20:04

A User


People also ask

How do you catch exceptions in Python?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

How do I return an empty data frame?

This is the simplest and the easiest way to create an empty pandas DataFrame object using pd. DataFrame() function. In this method, we simply call the pandas DataFrame class constructor without any parameters which in turn returns an empty pandas DataFrame object.

How do you know if a data frame is empty?

Use DataFrame.empty attribute empty attribute to check if the given dataframe is empty or not.

How do you handle errors in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.


1 Answers

For Pandas<=0.22 (previous answer was given for Django), the solution is as proposed by @henrique-marciel but with the Pandas import. So

from pandas.core.groupby import DataError

and add the exception

except DataError:

For Pandas>=0.23, as noted by ytu, the API changed and the following import should be used instead:

from pandas.core.groupby.groupby import DataError
like image 198
Christian O'Reilly Avatar answered Sep 21 '22 12:09

Christian O'Reilly