微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何解决使用 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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?