Добавить столбец широты и долготы в существующий фрейм данных - PullRequest
0 голосов
/ 28 апреля 2020

Я не могу добавить столбец широты и долготы в существующий фрейм данных. Я извлек координаты из одного из столбцов Restaurant_Location из моего набора данных, используя следующий код.

location = [x for x in rest_df['Restaurant_Location'].unique().tolist() if type(x) == str]
latitude = []
longitude =  []
for i in range(0, len(location)):
    if(type(location[i]) == str):
        ctr=0
        while True:
            try:
                address = location[i] + ', Mumbai, India'
                geolocator = Nominatim(user_agent="ny_explorer")
                loc = geolocator.geocode(address)
                latitude.append(loc.latitude)
                longitude.append(loc.longitude)
                print('The geographical coordinate of location are {}, {}.'.format(loc.latitude, loc.longitude))
            except:
                ctr+=1
                if(ctr==7):
                    print(i)
                    latitude.append(address)
                    longitude.append(address)
                    break
                continue
            break

Я могу получить желаемый Выход

The geographical coordinate of location are 19.1840129, 72.8412155.
The geographical coordinate of location are 19.0583358, 72.8302669.

Но после успешного выполнения кода выше rest_df.head() не показывает location_latitude & location_longitude столбцы в моем фрейме данных, которые я хочу добавить в data- Рамка. Также в моем фрейме данных есть несколько других столбцов. Пожалуйста, дайте мне знать, где я делаю ошибку?

1 Ответ

0 голосов
/ 29 апреля 2020

Вот кусок кода, который должен работать, я удалил некоторые вещи, так как я не уверен, почему, но вы все равно можете вернуть их обратно, если вы делаете другие вещи в нем. new_df должен иметь все строки из вашего исходного кадра данных и добавлять два столбца, которые вы хотите. Я не смог проверить, так как у меня нет ваших данных, поэтому они могут опечататься, но идея есть

location = [x for x in rest_df['Restaurant_Location'].unique().tolist() 
            if type(x) == str]
latitude = []
longitude =  []
for i in range(0, len(location)):
    # remove things that does not seem usefull here
    try:
        address = location[i] + ', Mumbai, India'
        geolocator = Nominatim(user_agent="ny_explorer")
        loc = geolocator.geocode(address)
        latitude.append(loc.latitude)
        longitude.append(loc.longitude)
        print('The geographical coordinate of location are {}, {}.'.format(loc.latitude, loc.longitude))
    except:
        # in the case the geolocator does not work, then add nan element to list
        # to keep the right size
        latitude.append(np.nan)
        longitude.append(np.nan)
# create a dataframe with the locatio, latitude and longitude
df_ = pd.DataFrame({'Restaurant_Location':location, 
                    'location_latitude': latitude,
                    'location_longitude':longitude})
# merge on Restaurant_Location with rest_df to get the column 
new_df = rest_df.merge(df_, on='Restaurant_Location', how='left')
...