KeyError Pandas – How To Fix
Pandas KeyError handling strategies
Pandas KeyError is frustrating. This error happens because Pandas cannot find what you’re looking for.
To fix this either:
- Preferred Option: Make sure that your column label (or row label) is in your dataframe!
- Error catch option: Use df.get(‘your column’) to look for your column value. No error will be thrown if it is not found.
Pseudo code: Check to see if a column is in your dataframe, if not, return the default value.
Pandas KeyError
In most cases, think of ‘key’ as the same as ‘name.’ Pandas is telling you that it can not find your column name. The preferred method is to *make sure your column name is in your dataframe.*
OR if you want to try and catch your error, you can use df.get(‘your_column’). However, if you don’t know what columns are in your dataframe…do you really know your data?
It’s best to head back upstream with your code and debug where your expectations and dataframe columns mismatch.
Try, Except
For a general solution, you can use the Try Except
convention to catch errors in your code. However, beware. Using a blanket Try/Except clause is dangerous and poor code practice if you do not know what you are doing.
If you are ‘catching’ general errors with try/except, this means that anything can slip through your code. This could result in unexpected errors getting through and a web of complexity.
Goal: Try to never let the reality of your code get too far away from the expectations of your code.
Let’s take a look at a sample: