我正在尝试使用Google的反向地理编码API来获取城市、州和国家的250个纬度和经度坐标列表。熊猫数据框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
:相关问题 更多 >
编程相关推荐