我有一些代码可以从Google Maps API返回一列回复。我只想从下面的位置键中选择纬度和经度,并将浮点数放入单独的列中(参见粗体文本):
[{'address_components':
[{'long_name': 'Winneba', 'short_name': 'Winneba', 'types': ['locality',
'political']}, {'long_name': 'Awutu', 'short_name': 'Awutu', 'types':
['administrative_area_level_2', 'political']}, {'long_name': 'Central',
'short_name': 'Central', 'types': ['administrative_area_level_1',
'political']}, {'long_name': 'Ghana', 'short_name': 'GH', 'types':
['country', 'political']}], 'formatted_address': 'Winneba, Ghana',
'geometry': {'bounds': {'northeast': {'lat': 5.404194800000001, 'lng':
-0.6021021999999999}, 'southwest': {'lat': 5.3282471, 'lng':
-0.6561327000000001}},
**'location': {'lat': 5.3622295, 'lng': -0.6298922}**,
'location_type': 'APPROXIMATE', 'viewport': {'northeast': {'lat':
5.404194800000001, 'lng': -0.6021021999999999}, 'southwest': {'lat':
5.3282471, 'lng': -0.6561327000000001}}}, 'place_id': 'ChIJG-Pj_-
g03g8RyVpI4vxYGko', 'types': ['locality', 'political']}]
我尝试了一些不同的方法,包括to_json,但这会导致奇怪的行为,其中json应用于数据帧中的每一行。因此,每行都有我的数据集中所有城市的json
这是数据框,数据:
所以我想从最后一列中只提取位置元素,然后有一列用于纬度,另一列用于经度
我有以下代码,转换为str的两种方式都不起作用:
data['geocode_result'] = data['geocode_result'].astype('str')
# data['geocode_result'] = data['geocode_result'].astype('|S')
string= data['geocode_result']
re.search(r'\'location\'\: \{\'lat\'\: (\d*.\d*)', string).group(1)
它抛出错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-ca085f711fda> in <module>()
2 # data['geocode_result'] = data['geocode_result'].astype('|S')
3 string= data['geocode_result']
----> 4 re.search(r'\'location\'\: \{\'lat\'\: (\d*.\d*)', string).group(1)
C:\Users\[ I deleted this] in search(pattern, string, flags)
180 """Scan through string looking for a match to the pattern, returning
181 a match object, or None if no match was found."""
--> 182 return _compile(pattern, flags).search(string)
183
184 def sub(pattern, repl, string, count=0, flags=0):
TypeError: expected string or bytes-like object
有谁知道我做错了什么?
非常感谢
以下完整代码:
import googlemaps
from datetime import datetime
import requests
import pandas as pd
import numpy as np
import re
gmaps = googlemaps.Client(key='API KEY')
download_path = 'C:\\Users\\username\\Documents\\'
data = pd.read_csv(download_path+'Ghana cities test.csv')
# The above is the spreadsheet containing city names that I want to
look up using the Google Maps API
city = data['city']
country = data['country']
ghana_city = city + ', ' + country
# The above combines city and country to allow for better searching
data['ghana_city'] = ghana_city
data['ghana_city'] = data['ghana_city'].astype('str')
data['geocode_result'] = data['ghana_city'].map(gmaps.geocode)
# Above searches Google API for every single||country combination and
returns the Google search results - from this I want the location