pythonpandasgpsgpx

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


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.


Solution

  • 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 xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>