Home >Backend Development >Python Tutorial >How to Convert Google Maps Elevation JSON Data to a Pandas DataFrame?
JSON to Pandas DataFrame: Converting Elevation Data
This article addresses the issue of transforming JSON elevation data obtained from Google Maps API into a tabular Pandas DataFrame.
The JSON data resembles the following format:
{ "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"', }
The goal is to extract the elevation, latitude, and longitude data into a DataFrame with columns titled "Elevation," "Latitude," and "Longitude."
The initially attempted method of pd.read_json(elevations) fails to produce the desired result. However, an improved approach utilizes the json_normalize() function from Pandas, which flattens the JSON data into a DataFrame. The code is as follows:
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'])
This operation generates the desired DataFrame format with three columns: "Elevation," "Latitude," and "Longitude."
The above is the detailed content of How to Convert Google Maps Elevation JSON Data to a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!