Search code examples
pythonpandaskeyerror

Confusing Key Errors in Pandas


I am encountering various Key Errors when I am running various commands in Python and I have no idea why this is happening. I understand that key errors are caused when a dictionary key can't be found, but to my knowledge the keys I'm calling are in the dataset.

Example: I've uploaded and cleaned my dataframe. I run the command:

df['LOB']=df['LOB'].astype(object) which works (I needed to change the datatype).

However, once I try to filter my data on this field I get the following:

df=df['LOB'!='Triggered']

KeyError: True

I also am running other commands such as groupby, and even created a sub table with only a few columns but am constantly getting various key errors.

I'm extremely confused and was hoping somebody could help out here.

I can provide further details as well.

Thanks a lot!!!


Solution

  • df=df['LOB'!='Triggered'] is wrong. Key error exception is what is raised when you try to access a key that isn't in a dictionary or a column. Python is checking if the name inside the brackets ('LOb'!='Triggered) is a column of df, since the column is LOB, it raises they key error.

    df['LOB']!='Triggered' is going to return a series of True or False wether if the row fills the condition or not.

    Then if you want to get all rows that fill this condition you have to do this: df[df['LOB']!='Triggered']. Basically here you are selecting all rows where the index is equal to True.

    If you want to store in a new dataframe just df = df[df['LOB']!='Triggered'].

    If you have any doubts about other commands just let us know.