JSON到pandas DataFram

2024-04-25 03:53:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是沿着经纬度坐标指定的路径从google maps 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"',
 '}']

当放入数据帧时,我得到的是:

enter image description here

pd.read_json(elevations)

我想要的是:

enter image description here

我不确定这是否可能,但我主要寻找的是一种方法,能够将高程、纬度和经度数据放在一个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

最终的数据帧具有列纬度、经度、高程

enter image description here


Tags: 数据importjsonrequestlocationresultelurlopen
3条回答

您可以首先在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)

你也可以避免将数据转储回字符串,我假设Panda可以直接从一个字典创建一个数据帧(我很久没用过它了:p)

看看这个剪子。

# 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)

希望有帮助:)

我用pandas 0.13中包含的json_normalize()找到了一个简单快捷的解决方案。

from urllib2 import Request, urlopen
import json
from pandas.io.json import json_normalize

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)
json_normalize(data['results'])

这提供了一个很好的扁平数据框架,其中包含我从Google Maps API获得的json数据。

相关问题 更多 >