내가하려는 것은 다음과 같이 위도 및 경도 좌표로 지정된 경로를 따라 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"',
 '}']
DataFrame으로 넣을 때 여기에 내가 얻는 것이 있습니다.

pd.read_json(elevations)그리고 여기 내가 원하는 것입니다 :

이것이 가능한지 확실하지 않지만 주로 내가 찾고있는 것은 판다 데이터 프레임에 고도, 위도 및 경도 데이터를 함께 넣을 수있는 방법입니다 (멋진 mutiline 헤더가 필요하지 않음).
이 데이터로 작업하는 데 도움이되거나 조언을 해줄 수 있다면 좋을 것입니다! 이전에 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
열 위도, 경도, 고도를 가진 데이터 프레임을 종료합니다.

답변
에 json_normalize()포함 하여 사용하려는 것에 대한 빠르고 쉬운 솔루션을 찾았 습니다 pandas 1.01.
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 데이터가 포함 된 멋진 데이터 프레임을 제공합니다.
답변
이 조각을 확인하십시오.
# 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)
그것이 도움이되기를 바랍니다 🙂
답변
먼저 파이썬 사전에서 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)
답변
python3.x지원되지 않는 새로운 답변의 승인 된 답변urllib2
from requests import request
import json
from pandas.io.json import json_normalize
path1 = '42.974049,-81.205203|42.974298,-81.195755'
response=request(url='http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false', method='get')
elevations = response.json()
elevations
data = json.loads(elevations)
json_normalize(data['results'])
답변
문제는 데이터 프레임에 작은 dict가 포함 된 dict가 포함 된 열이 여러 개 있다는 것입니다. 유용한 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')
답변
허용 된 답변의 최적화 :
수락 된 답변에는 기능상의 문제가 있으므로 urllib2에 의존하지 않는 코드를 공유하고 싶습니다.
import requests
from pandas.io.json import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
r = requests.get(url)
dictr = r.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)
산출:
        _id                    HourUTC               HourDK  ... ElbasAveragePriceEUR  ElbasMaxPriceEUR  ElbasMinPriceEUR
0    264028  2019-01-01T00:00:00+00:00  2019-01-01T01:00:00  ...                  NaN               NaN               NaN
1    138428  2017-09-03T15:00:00+00:00  2017-09-03T17:00:00  ...                33.28              33.4              32.0
2    138429  2017-09-03T16:00:00+00:00  2017-09-03T18:00:00  ...                35.20              35.7              34.9
3    138430  2017-09-03T17:00:00+00:00  2017-09-03T19:00:00  ...                37.50              37.8              37.3
4    138431  2017-09-03T18:00:00+00:00  2017-09-03T20:00:00  ...                39.65              42.9              35.3
..      ...                        ...                  ...  ...                  ...               ...               ...
995  139290  2017-10-09T13:00:00+00:00  2017-10-09T15:00:00  ...                38.40              38.4              38.4
996  139291  2017-10-09T14:00:00+00:00  2017-10-09T16:00:00  ...                41.90              44.3              33.9
997  139292  2017-10-09T15:00:00+00:00  2017-10-09T17:00:00  ...                46.26              49.5              41.4
998  139293  2017-10-09T16:00:00+00:00  2017-10-09T18:00:00  ...                56.22              58.5              49.1
999  139294  2017-10-09T17:00:00+00:00  2017-10-09T19:00:00  ...                56.71              65.4              42.2 
PS : API는 덴마크 전기 가격입니다
답변
다음은 JSON을 DataFrame으로 변환하는 작은 유틸리티 클래스입니다.
# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize
class DFConverter:
    #Converts the input JSON to a DataFrame
    def convertToDF(self,dfJSON):
        return(json_normalize(dfJSON))
    #Converts the input DataFrame to JSON 
    def convertToJSON(self, df):
        resultJSON = df.to_json(orient='records')
        return(resultJSON)
