Python GeoPandas – How to Convert LineString UTM Data to LatLong

geopandaspython

I have a few shapely.linestring objects that are read into geopandas with the call:

piped = gpd.read_file("Pipes.dbf")

In the geometry column the values are in UTM. I have identified the sector as 44Q and I can use utm to extract the lat/long for a single value. I'm pretty new to using Geopandas but was hoping there was an .apply where I could duplicate and convert the linestring objects into a list of tuples and store them in another column.

Example row value: LINESTRING(376753.3276983045 2042051.6105498213, 376764.03744285746 2042051.728052152)

I'd like to have a corresponding column called say lat_long that contains the same information from the linestring column but in a the format [(18.465193133286725, 73.83275226395054),(18.465194819587577, 73.83285367143624)]

def utm_to_latlon(vals, utm_lon, utm_lat):
"""Function to convert UTM TO lat long
   returns a tuple of latlong
"""
    return utm.to_latlon(vals[0], vals[1], zone_number=utm_lon, zone_letter=utm_lat)

Best Answer

You can use this script:

import utm
import geopandas as gpd

df = gpd.read_file("PATH/TO/Pipes.shp")

def utm_to_latlon(coords, zone_number, zone_letter):
    easting = coords[0]
    northing = coords[1]
    return utm.to_latlon(easting, northing, zone_number, zone_letter)

# Using nested list comprehension
df ["lat_lon_tuple"] = [[utm_to_latlon(xy, 44, "N") for xy in tuple(geom.coords)] for geom in df.geometry]

print(df)

OUTPUT:

    geometry                                                                            lat_lon_tuple
0   LINESTRING (252116.471 2510591.765, 253788.235 2510764.706)                         [(22.68435038429163, 78.5872648049902), (22.686155695429978, 78.60349856208599)]
1   LINESTRING (253651.765 2508544.412, 254651.765 2508544.412, 255151.765 2510544.412) [(22.66609572779645, 78.60251971456782), (22.666241062086172, 78.61224530186976), (22.684365437082395, 78.61679603925353)]