convert pandas DataFrame or list of longitude and latitudes to a gpx file in python

Question:

I have longitude and latitude values in a pandas DataFrame but I want to convert it to a gpx file so I can visualize it later in google maps. how can I do that with python ? I took a look at the gpxpy library but the examples shows how to load or read a gpx file and I want to do the opposite. I want to read a csv file and turn it to gpx file or directly convert from pandas Dataframe.

Asked By: basilisk

||

Answers:

Please refer to this: https://pypi.org/project/gpxpy/

I guess you will need the package for your task. And then you could use their provided example:

import gpxpy
import gpxpy.gpx

with open("outfile.gpx", "w") as f:
    f.write( gpx.to_xml())

Converting a pandas df to xml is described here:
How do convert a pandas/dataframe to XML?

Answered By: Fourier

What about this: (adapted from the create-file section of https://pypi.org/project/gpxpy/)

# import pandas as pd
# import numpy as np

# df = pd.DataFrame(90*np.random.random((5, 2)))

# print(df)

import gpxpy
import gpxpy.gpx

gpx = gpxpy.gpx.GPX()

# Create first track in our GPX:
gpx_track = gpxpy.gpx.GPXTrack()
gpx.tracks.append(gpx_track)

# Create first segment in our GPX track:
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)

# Create points:
for idx in df.index:
    gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(df.loc[idx, 0], df.loc[idx, 1]))

# print(gpx.to_xml())

with open('output.gpx', 'w') as f:
    f.write(gpx.to_xml())

example data of code above:

dataframe:

#            0          1
# 0  76.297096  86.421851
# 1  26.041973   5.265947
# 2  24.292204  37.074964
# 3   2.033896  19.136688
# 4  13.527561  25.136911

XML data:

# <?xml version="1.0" encoding="UTF-8"?>
# <gpx   xsi_schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="gpx.py -- https://github.com/tkrajina/gpxpy">
#   <trk>
#     <trkseg>
#       <trkpt lat="76.29709588485436" lon="86.42185081600744">
#       </trkpt>
#       <trkpt lat="26.041973450515652" lon="5.2659474962495985">
#       </trkpt>
#       <trkpt lat="24.292204051893012" lon="37.07496383039659">
#       </trkpt>
#       <trkpt lat="2.033895516776183" lon="19.1366881465948">      </trkpt>
#       <trkpt lat="13.527560800715804" lon="25.136910635806306">
#       </trkpt>
#     </trkseg>
#   </trk>
# </gpx>
Answered By: SpghttCd

Question:

This code creates a single track with a single segment.

How do you create a gpx file with multiple tracks and segments?

for example:

df = [ id, date, lat, long]

tracks = id

segments = date

points = (lat, long)

Thanks!

Answered By: Jessica Morris
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.