JSON到pandasDataFrame

我想要做的是从纬度和经度坐标指定的path,从谷歌地图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数据框(不必具有花哨的多线头)。

如果任何人能够帮助或提供一些build议,使用这个数据将是伟大的! 如果你不能说我以前没有用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 

结束具有列纬度,经度,高程的dataframe

在这里输入图像说明

我发现了一个快速简便的解决scheme,使用了包含在最新版pandas0.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']) 

这给我一个很好的扁平化的数据框,我从谷歌地图API获得的JSON数据。

检查这剪断了。

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

希望能帮助到你 :)

你可以先在Python的dictionnary中导入你的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'] 

重buildjsonstring:

 elevations = json.dumps(data) 

最后:

 pd.read_json(elevations) 

你也可以避免把数据转储回string,我假设Panda可以直接从一个字典中创build一个DataFrame(我很久没用过了:p)

问题是你在数据框中有几列包含有较小字典的字典。 有用的Json通常是嵌套的。 我一直在写小函数,把我想要的信息放到一个新的列中。 这样,我有我想要使用的格式。

 for row in range(len(data)): #First I load the dict (one at a time) n = data.loc[row,'dict_column'] #Now I make a new column that pulls out the data that I want. data.loc[row,'new_column'] = n.get('key')