Python Forum
KeyError when merging - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: KeyError when merging (/thread-15510.html)



KeyError when merging - kbrummert - Jan-20-2019

I get a KeyError when merging two data frames, even though I have confirmed that both have dt as a name and both are of the same data type.

df_hown.head()
Out[118]: 
           dt  hown_rt
0  1980-01-01     65.5
1  1980-04-01     65.6
2  1980-07-01     65.6
3  1980-10-01     65.6
4  1981-01-01     65.6

df_vcy.head()
Out[119]: 
           dt  vcy_rt
0  1956-01-01     6.2
1  1956-04-01     5.9
2  1956-07-01     6.3
3  1956-10-01     5.8
4  1957-01-01     5.3



df_hown.dtypes
Out[132]: 
dt          object
hown_rt    float64
dtype: object

df_vcy.dtypes
Out[133]: 
dt         object
vcy_rt    float64
dtype: object


# merge dataframes to create new one
df_merged = pd.merge(df_hown,
                 df_vcy[['vcy_rt']],
                 on=['dt','dt'])

...

KeyError: 'dt'



RE: KeyError when merging - stullis - Jan-20-2019

It could be the slice on df_vcy. I imagine that it's only passing the "vcy_rt" column into the function and getting an error because the "dt" column has not been passed in.


RE: KeyError when merging - kbrummert - Jan-20-2019

That worked. Thanks.

Strange, because the original code example I was basing it on indicated that the join fields were implicit from the original dfs as they would be in SQL, and would not have to be explicitly listed in the function.

df_merged = pd.merge(df_hown[['dt', 'hown_rt']],
                 df_vcy[['dt', 'vcy_rt']],
                 on=['dt','dt'])

df_merged.head()
Out[140]: 
          dt  hown_rt  vcy_rt
0 1980-01-01     65.5     5.2
1 1980-04-01     65.6     5.6
2 1980-07-01     65.6     5.7
3 1980-10-01     65.6     5.0
4 1981-01-01     65.6     5.2