Python Forum

Full Version: Pandas merge question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I hope you are all having a good day. I want to know why my merge below is returning the key error that is stated below my code. Any help would be appreciated.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

dict1={'eggs':(1,7,44,76,23,56,22,21,20,11,12,81),'month':('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec')}

dict2={'bread':(22,43,17,9,22,16,71,82,24,34,54,45),'months':('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec')}

df1=pd.DataFrame(dict1)

df2=pd.DataFrame(dict2)

df1.columns.values[1]='months'

pd.merge(left=df1,right=df2,on='months')
KeyError: 'months'
Your example works for me. Perhaps you forgot to run line 15 (that renames month column as months column), so there was no 'months' key in df1 and merge failed?
The code works perfectly with this output
Output:
eggs months bread 0 1 jan 22 1 7 feb 43 2 44 mar 17 3 76 apr 9 4 23 may 22 5 56 jun 16 6 22 jul 71 7 21 aug 82 8 20 sep 24 9 11 oct 34 10 12 nov 54 11 81 dec 45
It appears that the error you get is because you have not renamed the month column in first dataframe to months
Check out this pandas tutorial to know more