A User
A User

Reputation: 862

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?

Upvotes: 11

Views: 15287

Answers (3)

Roméo Després
Roméo Després

Reputation: 2173

The safest and shortest way is:

from pandas.core.base import DataError

or, for pandas >= 1.5.0,

from pandas.errors import DataError

(as indicated by @Craig Austin in the comments)


Why

pandas >= 1.5.0

This error is now part of the official API, so it shouldn't move from pandas.errors.

pandas < 1.5.0

In pandas.core.base we can find the actual place where DataError is defined:

class DataError(Exception):
    pass

pandas.core.groupby.groupby simply imports it as follows, which is more likely to break after some update:

from pandas.core.base import (
    DataError,
    PandasObject,
    SelectionMixin,
)

Upvotes: 3

Christian O&#39;Reilly
Christian O&#39;Reilly

Reputation: 2054

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

Upvotes: 13

Henrique Maciel
Henrique Maciel

Reputation: 51

I had the same problem, you can solve as follows:

from django.db import DataError

Add the exception

except DataError:

I managed to solve this way, below is the link of the documentation.

Documentation

Upvotes: 5

Related Questions