Home > Back-end >  Pandas DataFrame updating columns
Pandas DataFrame updating columns

Time:10-27

I'm trying to get longitudes and latitudes of venues via physical addresses I have.

To do so, I'm using GoogleMaps API.

While executing the following code, I'd been trying to directly insert the longitude, and latitude into the empty columns of dataframe.

  • In the df['ADDR'] there are physical addresses stored for 1,500 venues.
    import pandas as pd
    import googlemaps
    
    locations = df['ADDR']
    df['lat'] = ""
    df['lng'] = ""
    
    i = 0
    for location in locations:
        i = i   1
        try:
            print("%d indexing %s location" % (i, location))
            geo_location = maps.geocode(location)[0].get('geometry')
            print(geo_location['location']['lat'], geo_location['location']['lng'])
            df['lat'].append(geo_location['location']['lat'])
            df['lng'].append(geo_location['location']['lng'])
            print(df)
        
            except IndexError:
                print("Address was wrong...")
            except Exception as e:
                print("Unexpected error occurred.", e) 

When I execute it, I get "cannot concatenate object of type '<class 'float'>'; only Series and DataFrame objs are valid".

I first thought this was because when I get the information from GoogleMaps, it is in json format.

So, I tried adding the following

geo_lat = pd.to_Series(geo_location['location']['lat'], geo_location(['location']['lng'])

Then I get an error "list indices must be integers or slices, not str".

Could any one provide a way to insert in values to df['lat'], df['lng'] next to physical addresses df['ADDR'] properly?

CodePudding user response:

To add new columns and update its value in a DataFrame you could use this in your loop, without defining a priori the columns:

for i, location in enumerate(locations):
    df.at[i, 'lat'] = geo_location['location']['lat']
    df.at[i, 'lng'] = geo_location['location']['lng']
  • Related