Search code examples
pythonpandasdataframegeolocationfolium

DataFrame: from string dictionnary in one columns to floats in two column {'latitude': '34.04', 'longitude': '-118.24'}


I have a pandas DataFrame df with a column latlng. The rows in this column have the format

{'latitude': '34.041005', 'longitude': '-118.249569'}.

In order to be able to add markers to a map (using folium librairie), I would like to create two columns 'latitude' and longitude which in this example would contain respectively 34.041005 and -118.249569.


EDIT: Managed to have it working with this first step: df['latlng'] = df['latlng'].map(eval)


Solution

  • You can use pd.json_normalize to avoid apply which is costly:

    In [684]: df_out = pd.json_normalize(df.latlong)
    In [686]: df_out
    Out[686]: 
        latitude    longitude
    0  34.041005  -118.249569
    1  30.041005  -120.249569
    

    Then you can concat these columns back to df like below:

    pd.concat([df.drop('latlong', axis=1), df_out], axis=1)