我正在使用地理库向谷歌地图发送API请求,以获取熊猫数据帧中每个地址的区域名称,然后尝试将其存储在自己的列中。
import geopy
import numpy as np
from geopy.geocoders import GoogleV3
def get_area(address):
geolocator = GoogleV3(api_key=api_key, domain='maps.googleapis.com', scheme=None, client_id=None,
secret_key=None,
user_agent=None )
geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
data = geocode((address), timeout=None)
#print(data.raw)
area = []
for item in data.raw['address_components']:
if data.raw is None:
area.append(None)
continue
found = False
typs = set(item['types'])
if typs == set(['neighborhood', 'political']):
print(item['long_name'])
area.append(item['long_name'])
found = True
break
if not found:
area.append(None)
return area
df_test['Area'] = df_test[['L_Address']].apply(lambda row: get_area(row['L_Address']), axis=1)
为了清楚起见,这就是谷歌地图的原始响应:
{'address_components': [{'long_name': '7155', 'short_name': '7155', 'types': ['street_number']}, {'long_name': 'Hall Road', 'short_name': 'Hall Rd', 'types': ['route']}, {'long_name': 'Newton', 'short_name': 'Newton', 'types': ['neighborhood', 'political']}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 49.1335569802915, 'lng': -122.8458199197085}, 'southwest': {'lat': 49.1308590197085, 'lng': -122.8485178802915}}}
这是我对上面代码的回应:
0 [None, None, None, None, None, None, None]
1 [None, None, None, None, None, None, None]
2 [None, None, None, None, None, None, None]
3 [None, None, South Westminster]
4 [None, None, Whalley]
5 [None, None, None, None, None, None, None]
6 [None, None, None, None, None, None, None]
7 [None, None, Newton]
8 [None, None, Whalley]
9 [None, None, None, None, None, None, None]
10 [None, None, None, None, None, None, None]
所以我知道我把循环中的某个地方搞砸了,因为每行只需要一个区域名称。有什么建议吗?
我想我发现了问题。如果你只需要每行一个值,那么把你的循环改成这样:
for item in data.raw['address_components']:
if data.raw is None:
area.append(None)
break
found = False
typs = set(item['types'])
if typs == set(['neighborhood', 'political']):
print(item['long_name'])
area.append(item['long_name'])
found = True
break
if not found:
area.append(None)
break