Home > Backend Development > Python Tutorial > How to Efficiently Convert Nested Google Maps Elevation JSON Data into a Pandas DataFrame?

How to Efficiently Convert Nested Google Maps Elevation JSON Data into a Pandas DataFrame?

Patricia Arquette
Release: 2024-12-22 08:14:13
Original
803 people have browsed it

How to Efficiently Convert Nested Google Maps Elevation JSON Data into a Pandas DataFrame?

Converting JSON Elevation Data to Pandas DataFrame

Objective: Extract elevation data from Google Maps API and organize it in a Pandas DataFrame.

Problem:

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"
}
Copy after login

Importing this JSON into a Pandas DataFrame directly leads to a scattered structure.

Solution:

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
Copy after login

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'])
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template