Data type error while merging pandas dataframes

Viewed 250

I have two Data Frames as below. I want to check two columns, named lon and lat in these data frames, and if they match, then merge them together. What I mean is that I want to read the DF1 data (store id and store name) into DF2 data (because the DF2 is much bigger) if these two column are matched.

DF1
       store_id    store_name          lon                    lat
0      place_1     McDonald's        13.31543.              52.67649
1      place_2     McDonald's   13.4683480000000007     52.5471599999999981

DF2
     device_id   lat    lon      utc_timestamp      addidas  apple.         bmw  female        male 
0       1   52.67649    13.31543    1.609460e+12    97745.0 141158.0    78690.0   85002.0       2.0 
1       1   52.67649    13.31542    1.609460e+12    97745.0 141158.0    78690.0   85002.0       2.0 
2       2   52.57837    13.58217    1.609459e+12    45843.0 164532.0    114955.0  85003.0       3.0 


I wrote the code below : but it gives me error , can any one help me?

df3 = df1.merge(df2, how = 'inner', on = ['lat', 'lon'])

ERROR: You are trying to merge on object and float64 columns. If you wish to proceed you should use pd.concat

I use the pd.concat, but it does not work again.

1 Answers

One of the columns is of object dtype, while the other is of float64. You have to pick a data type. Assuming we 're too lazy to find which column is of which type:

df1['lat'] = df1.lat.astype(float)
df2['lat'] = df2.lon.astype(float)

Or

df1['lat'] = df1.lat.astype(str)
df2['lat'] = df2.lon.astype(str)
Related