2

I want to geocode a number of universities in Europe (stored in a csv file). The csv file contains only one column (Name). However, I am yet to complete the work, since my code contains bugs. When I ran the code, I got ValueError: Columns must be same length as key. This occurred on the last line. How do I solve this?

Here's a sample of the code I used:

from geopy.geocoders import Nominatim

import pandas as pd

import numpy as np

geolocator = Nominatim(user_agent = 'ed') 

universities = pd.read_csv("Z:/data/top_universities.csv")

def my_geocoder(row):
    try:
        point = geolocator.geocode(row).point
        return pd.Series({'Latitude': point.latitude, 'Longitude': point.longitude})
    except:
        return None

universities[['Latitude', 'Longitude']] = universities.apply(lambda x: my_geocoder(x['Name']), axis=1)
1

1 Answer 1

3

pandas is expecting two values (columns) to be returned as you specified two keys ['Latitude', 'Longitude'].

However, when there's an exception, e.g. no geocoding result, you only return a single value None. So you get ValueError: Columns must be same length as key

Return two values when there's a geocoding error, i.e. None, None and you can filter them out later:

from geopy.geocoders import Nominatim
import pandas as pd
import numpy as np


def my_geocoder(row):
    try:
        point = geolocator.geocode(row).point
        return pd.Series({'Latitude': point.latitude, 'Longitude': point.longitude})
    except:
        return None, None


geolocator = Nominatim(user_agent = 'ed')
universities = pd.read_csv("test.csv")
universities[['Latitude', 'Longitude']] = universities.apply(lambda x: my_geocoder(x['Name']), axis=1)

print(universities.head())

Output:

                             Name   Latitude   Longitude
0  Australian National University -35.281213  149.116779
1            University of Sydney -33.896083  151.184661
2                            RMIT -37.682204  145.068329
3              No Such University        NaN         NaN
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.