Running Python Code Despite Keyerror
I get a KeyError for one of the entries in the dataframe, but I would like the code to continue with the other entries which seem to have not problem. I have been reading about the
Solution 1:
Assuming a dataframe df
, this is how you handle the KeyError
exception:
import pandas
df = pandas.DataFrame()
try:
print df[0]
except KeyError as exc:
print"Caught KeyError: {}".format(exc)
Output
Caught KeyError: 0
The same also works on dictionaries. You can see here that the exception is bound to exc
in the except
clause and can be accessed within the exception handler. In Python 3, exc
is not accessible outside of the except
clause; in Python 2 it is accessible (but you should follow the Python 3 way).
Solution 2:
The basic form of exception handling in python uses try:
try:
#code which gives key error (replace pass with your code)passexcept KeyError:
#do some exception handling here (or just pass)pass
Post a Comment for "Running Python Code Despite Keyerror"