Objective: Extract elevation data from Google Maps API and organize it in a Pandas DataFrame.
A JSON data obtained from the Google Maps API elevation service contains nested information in the format:
{ "results" : [ { "elevation" : 243.3462677001953, "location" : { "lat" : 42.974049, "lng" : -81.205203 }, "resolution" : 19.08790397644043 }, ... ], "status" : "OK" }
Importing this JSON into a Pandas DataFrame directly leads to a scattered structure.
Using nested list extraction:
To manually separate the elevation, latitude, and longitude data:
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
This creates a DataFrame with columns latitude, longitude, and elevation.
Using json_normalize (Pandas v1.01 ):
A simpler approach using Pandas' json_normalize:
df = pd.json_normalize(data['results'])
This flattens the JSON data into a DataFrame with columns for each key in the nested structure.
The above is the detailed content of How to Efficiently Convert Nested Google Maps Elevation JSON Data into a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!