pythondataframeutm

Lat/Long to UTM conversion failing for dataframe


The error OutOfRangeError: latitude out of range (must be between 80 deg S and 84 deg N)" appears when I use the utm.from latlon() function on a dataframe.

When I try it for a single lat/long, however, it returns the result. I'm not sure what's going on.

e.g. dataframe

    Lat          Lon
0   49.183630   -121.936812
1   43.901052   -78.939154
2   43.887452   -78.871573
3   42.882137   -82.445210
4   43.372565   -79.762019

My Lat/Long is not reversed, as I checked.

Let's say utm function is defined as:

def f(x,y):
  return utm.from_latlon(x,y)

And I am calling the function as:

dataframe.apply(lambda row: f(row['Lat'], row['Lon']), axis=1)


Solution

  • Assuming you use utm package:

    import pandas as pd
    import utm
    
    df = pd.read_csv('latlon.csv')
    df['utm'] = df.apply(lambda row: utm.from_latlon(*row), axis=1)
    utm_cols = ['easting', 'northing', 'zone_number', 'zone_letter']
    for n, col in enumerate(utm_cols):
        df[col] = df['utm'].apply(lambda location: location[n])
    df = df.drop('utm', axis=1)
    print(df)
    

    output

             Lat         Lon        easting      northing  zone_number zone_letter
    0  49.183630 -121.936812  577477.332853  5.448413e+06           10           U
    1  43.901052  -78.939154  665502.266670  4.862947e+06           17           T
    2  43.887452  -78.871573  670968.577419  4.861574e+06           17           T
    3  42.882137  -82.445210  381977.464091  4.748739e+06           17           T
    4  43.372565  -79.762019  600294.444939  4.802933e+06           17           T