user5421875
user5421875

Reputation:

Error during iteration on dataframe rows

I'm trying to define location given the latitude and longitude, that I have in the dataframe:

    lat        long
  40.712784   -74.005941
  55.755826   37.617300
  41.902783   12.496366

I'm using geopy library, and I'd like store the retrieving locations in new third column of existing dataframe. to have smth like:

    lat        long        location 
  40.712784   -74.005941   New-York
  55.755826   37.617300    Moscow
  41.902783   12.496366    Rome

The code that I execute is :

def take_location():
    geolocator = Nominatim()
    df['location']=''
    for row, index in df.iterrows():
        location= geolocator.reverse("%f, %f" % (row['lat'], row['long']))
        row['location']=location.address
    return df

Problem occurs on this line: ----> 6 location= geolocator.reverse("%f, %f" % (row['lat'], row['long'])) with following IndexError: invalid index to scalar variable. I suppose there could be something wrong with arguments, and extracting values from row cells

Upvotes: 2

Views: 151

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

DataFrame.iterrows() gives values in order - (index, row) - but you are assuming it to be coming in order (row,index) , which is wrong, and hence you are getting the issue. You should use -

for index, row in df.iterrows():
    location= geolocator.reverse("%f, %f" % (row['lat'], row['long']))
    row['location']=location.address

Upvotes: 1

Related Questions