Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pandas merge question
#1
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'
Reply
#2
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?
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pandas df inside a df question mbaker_wv 4 1,152 Dec-25-2022, 01:11 AM
Last Post: mbaker_wv
  Pandas usecols question rsearing 1 1,218 Aug-20-2022, 10:10 PM
Last Post: jefsummers
  Simple pandas question mcva 4 2,607 Dec-17-2021, 04:47 PM
Last Post: mcva
  Pandas question new2datasci 0 1,928 Jan-10-2021, 01:29 AM
Last Post: new2datasci
  Python pandas merge with or conditional Lafayette 0 2,149 May-07-2020, 07:34 PM
Last Post: Lafayette
  Pandas dataframe merge snmmat 1 2,096 Mar-09-2020, 06:56 PM
Last Post: jefsummers
  Pandas merge csv files karlito 2 3,139 Dec-16-2019, 10:59 AM
Last Post: karlito
  Counting Criteria in Pandas Question Koenig 1 2,138 Sep-30-2019, 05:16 AM
Last Post: perfringo
  Function question using Pandas smw10c 7 7,012 Feb-12-2019, 06:52 PM
Last Post: Nathandsn
  Simple pandas dataframe question popohoma 1 3,497 Jan-03-2019, 05:00 PM
Last Post: ashlardev

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020