Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Getting a Key Error when the Key Exists

I'm trying to join two dataframes in Pandas.

The first frame is called Trades and has these columns:

TRADE DATE
ACCOUNT
COMPANY
COST CENTER
CURRENCY

The second frame is called Company_Mapping and has these columns:

ACTUAL_COMPANY_ID
MAPPED_COMPANY_ID

I'm trying to join them with this code:

trade_df = pd.merge(left=Trades, right = Company_Mapping, how = 'left', left_on = 'COMPANY', right_on = 'ACTUAL_COMPANY_ID'

This returns:

KeyError: 'COMPANY'

I've double checked the spelling and COMPANY is clearly in Trades, and I have no clue what would cause this.

Any ideas?

Thanks!

like image 936
DixieFlatline Avatar asked May 03 '17 23:05

DixieFlatline


People also ask

Why am I getting a key error in pandas?

Pandas KeyError It generally happens when pandas cannot find the thing you're looking for. Usually this is to due a column it cannot find. It's simple to debug!

How do you fix key errors in Python?

When working with dictionaries in Python, a KeyError gets raised when you try to access an item that doesn't exist in a Python dictionary. This is simple to fix when you're the one writing/testing the code – you can either check for spelling errors or use a key you know exists in the dictionary.

How can pandas avoid key errors?

We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.

How do you solve KeyError 1 in Python?

The Python "KeyError: 1" exception is caused when we try to access a 1 key in a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.


2 Answers

Your Trades dataframe has a single column with all the intended column names mashed together into a single string. Check the code that parses your file.

like image 177
piRSquared Avatar answered Sep 30 '22 16:09

piRSquared


Make sure you read your file with the right seperation.

df = pd.read_csv("file.csv", sep=';')

or

df = pd.read_csv("file.csv", sep=',')
like image 33
Daniëlle Avatar answered Sep 30 '22 17:09

Daniëlle