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 except() option but don't know how to use it. Can you help
Asked
Active
Viewed 5,796 times
2 Answers
3
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).

mhawke
- 84,695
- 9
- 117
- 138
2
The basic form of exception handling in python uses try:
try:
#code which gives key error (replace pass with your code)
pass
except KeyError:
#do some exception handling here (or just pass)
pass
-
Thanks, this is just the fix I was looking for. I put the section of code that was giving the KeyError under try and passed if there was an exception – Ssank Apr 08 '15 at 15:02