我要做的是沿着纬度和经度坐标指定的路径从google地图API中提取高程数据,如下所示:
from urllib2 import Request, urlopen
import json
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
这给了我一个看起来像这样的数据:
elevations.splitlines()
['{',
' "results" : [',
' {',
' "elevation" : 243.3462677001953,',
' "location" : {',
' "lat" : 42.974049,',
' "lng" : -81.205203',
' },',
' "resolution" : 19.08790397644043',
' },',
' {',
' "elevation" : 244.1318664550781,',
' "location" : {',
' "lat" : 42.974298,',
' "lng" : -81.19575500000001',
' },',
' "resolution" : 19.08790397644043',
' }',
' ],',
' "status" : "OK"',
'}']
当作为DataFrame放入时,我得到的结果是:
pd.read_json(elevations)
这是我想要的:
我不确定这是否可能,但我主要寻找的是一种能够将海拔、纬度和经度数据放在一个pandas数据帧中的方法(不需要有花哨的多行头)。
如果有人能在使用这些数据方面提供帮助或建议,那就太好了!如果你看不出来我以前没怎么处理过json数据...
编辑:
这种方法并不那么吸引人,但似乎是有效的:
data = json.loads(elevations)
lat,lng,el = [],[],[]
for result in data['results']:
lat.append(result[u'location'][u'lat'])
lng.append(result[u'location'][u'lng'])
el.append(result[u'elevation'])
df = pd.DataFrame([lat,lng,el]).T
最终生成具有列纬度、经度、高程的数据帧
发布于 2014-01-22 02:17:22
我使用pandas 1.01
中包含的json_normalize()
找到了一个快速而简单的解决方案来满足我的需求。
from urllib2 import Request, urlopen
import json
import pandas as pd
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
df = pd.json_normalize(data['results'])
这提供了一个很好的扁平化数据帧,其中包含我从Google Maps API获得的json数据。
发布于 2017-06-18 01:04:41
看看这个片段。
# reading the JSON data using json.load()
file = 'data.json'
with open(file) as train_file:
dict_train = json.load(train_file)
# converting json dataset from dictionary to dataframe
train = pd.DataFrame.from_dict(dict_train, orient='index')
train.reset_index(level=0, inplace=True)
希望它能有所帮助:)
发布于 2014-01-14 10:19:36
您可以首先在Python字典中导入json数据:
data = json.loads(elevations)
然后动态修改数据:
for result in data['results']:
result[u'lat']=result[u'location'][u'lat']
result[u'lng']=result[u'location'][u'lng']
del result[u'location']
重建json字符串:
elevations = json.dumps(data)
最后:
pd.read_json(elevations)
您还可以避免将数据转储回字符串,我假设熊猫可以直接从字典创建DataFrame (我很长时间没有使用它了:p)
https://stackoverflow.com/questions/21104592
复制相似问题