如何解决使用 Google 反向地理编码 API 遍历 Pandas 数据框的问题?

问题描述

我正在尝试使用 Google 的反向地理编码 API 来获取城市、州和国家/地区的 250 个经纬度坐标列表。 pandas 数据框 df 包含 df['point'] 列中的位置坐标。我想将城市、州和国家作为新列添加到原始 df 中。下面的 python 代码非常适用于 state 和 country 列,但对于 city 列却失败了,因为 'city_list' 是两个短结果。我收到此错误

ValueError: Length of values (248) does not match length of index (250)

我一直在努力想办法解决这个问题。有没有办法将“错误添加到无法生成城市的两行的列表中?非常非常感谢您对此的帮助!!!

import googlemaps
import json
import pandas as pd

gmaps = googlemaps.Client(key='APIKEYHERE')

stored=[]
city_list=[]
state_list=[]
country_list=[]

for latlng in df['point']:
    r_geocode_result = gmaps.reverse_geocode((latlng))
    stored.append(r_geocode_result)
    address_components = r_geocode_result[0]['address_components']
    for address_type in address_components:
        flags = address_type.get('types',[])
        if 'locality' in flags:
            city = address_type['long_name']
            city_list.append(city)
        elif 'administrative_area_level_1' in flags:
            state = address_type['short_name']
            state_list.append(state)
        elif 'country' in flags and 'political' in flags:
            country = address_type['short_name']
            country_list.append(country)

# Convert lists into columns in original df
df['city'] = city_list
df['state'] = state_list
df['country'] = country_list

解决方法

显然创建的列表之一比数据框短。这可能发生,因为您只有 if 条件,而没有其他条件。因此,如果不满足 if 条件,您的代码不会附加任何内容。作为解决方案,您可以通过列表理解查找值,如果列表为空,则将 None 分配给该值。另外我建议使用 pd.apply:

import googlemaps
import pandas as pd

gmaps = googlemaps.Client(key='APIKEYHERE')

def get_location(latlng):
    r_geocode_result = gmaps.reverse_geocode((latlng))
    address_components = r_geocode_result[0]['address_components']

    city = [i['long_name'] for i in address_components if 'locality' in i['types']]
    city = city[0] if city else None

    state = [i['long_name'] for i in address_components if 'administrative_area_level_1' in i['types']]
    state = state[0] if state else None

    country = [i['long_name'] for i in address_components if all(elem in ['country','political'] for elem in i['types'])]
    country = country[0] if country else None

    return pd.Series([city,state,country])

df[['city','state','country']] = df['point'].apply(get_location)