Skip to content

Instantly share code, notes, and snippets.

@jonahadkins
Forked from alexkapps/dms_string_to_dd.py
Created March 18, 2016 21:23
Show Gist options
  • Save jonahadkins/63fa7eb8d40b4cb8d00c to your computer and use it in GitHub Desktop.
Save jonahadkins/63fa7eb8d40b4cb8d00c to your computer and use it in GitHub Desktop.
#converts DMS lat/long format columns like '89444400','89444400' to decimal degrees
#Author: Alex Kappel
import pandas as pd
#assigns file location
input_path = '~/Documents/temp/nbi_2014.csv'
#imports csv
df = pd.read_csv(input_path, low_memory=False, dtype=float, sep=',', encoding='ISO-8859-1')
#makes sure input is interpreted as string (for slicing)
df.latitude = df.latitude.astype(str)
df.longitude = df.longitude.astype(str)
#splits string into degree, min, sec columns
df['lat_degree'] = df['latitude'].str[0:2].astype(float)
df['lat_minute'] = df['latitude'].str[2:4].astype(float)
df['lat_second'] = df['latitude'].str[4:6].astype(float)
df['lon_degree'] = df['longitude'].str[0:2].astype(float)
df['lon_minute'] = df['longitude'].str[2:4].astype(float)
df['lon_second'] = df['longitude'].str[4:6].astype(float)
#conversion math
df['lat_decimal_degrees'] = df['lat_degree'] + ( df['lat_minute'] / 60 ) + ( df['lat_second'] / 3600 )
df['lon_decimal_degrees'] = df['lon_degree'] + ( df['lon_minute'] / 60 ) + ( df['lon_second'] / 3600 )
#subsets dataframe for final output columns
df = df[['latitude', 'longitude', 'lat_decimal_degrees', 'lon_decimal_degrees']]
#outputs csv
df.to_csv('dd_output.csv', encoding='utf-8', index=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment