0
votes

I'm trying to merge two dataframes together using .merge and "inner" to find common column, here are the two dataframes, 1st one,

     Year Month  Brunei Darussalam   ...  Australia   New Zealand   Africa 
0    1978   Jan                 na   ...       28421          3612      587
1    1978   Feb                 na   ...       13982          2521      354
2    1978   Mar                 na   ...       16536          2727      405
3    1978   Apr                 na   ...       16499          3197      736
4    1978   May                 na   ...       20690          5130      514
..    ...   ...                 ...  ...         ...           ...      ...
474  2017   Jul                5625  ...      104873         15358     6964
475  2017   Aug                4610  ...       75171         11197     6987
476  2017   Sep                5387  ...      100987         12021     5458
477  2017   Oct                4202  ...       90940         11834     5635
478  2017   Nov                5258  ...       81821          9348     6717

2nd one,

   Year Month
0  1980   Jul
1  1980   Aug
2  1980   Sep
3  1980   Oct
4  1980   Nov

I tried to use this input to initialize my command,

merge = pd.merge(dataframe,df, how='inner', on=['Year', 'Month'])
print(merge)

but I keep getting this ERROR,

Traceback (most recent call last):
  File "main.py", line 52, in <module>
    merge = pd.merge(dataframe,df, how='inner', on=['Year', 'Month'])
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/reshape/merge.py", line 74, in merge
    op = _MergeOperation(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/reshape/merge.py", line 672, in __init__
    self._maybe_coerce_merge_keys()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/core/reshape/merge.py", line 1193, in _maybe_coerce_merge_keys
    raise ValueError(msg)
ValueError: You are trying to merge on int64 and object columns. If you wish to proceed you should use pd.concat
1

1 Answers

0
votes

It means one column Year is numeric, second filled by strings.

So need same types like:

dataframe['Year'] = dataframe['Year'].astype(int)
df['Year'] = df['Year'].astype(int)
df1 = pd.merge(dataframe,df, how='inner', on=['Year', 'Month'])

Or:

dataframe['Year'] = dataframe['Year'].astype(str)
df['Year'] = df['Year'].astype(str)
df1 = pd.merge(dataframe,df, how='inner', on=['Year', 'Month'])