1

In the spirit of this questions: Converting pandas data frame with degree minute second (DMS) coordinates to decimal degrees I want to convert a longitude with the format, for instance, 18-23-34W to a decimal, i.e., -18.392778. I want to separate by the minus, -, and by uppercase.

The function in the link I have been trying, adapted to my necessities:

def dms2dd(s):
    degrees, minutes, seconds, direction = re.split('[A-Z-]+', s)
    dd = float(degrees) + float(minutes) / 60 + float(seconds) / (60 * 60)
    if direction in ('S', 'W'):
        dd *= -1
    return dd

The problem seems to be with the regex in degrees, minutes, seconds, direction = re.split('[A-Z-]+', s). I obtain the conversion but not the multiplication by -1, as it should be. Thx.

Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53
David
  • 1,155
  • 1
  • 13
  • 35

1 Answers1

4

Your seconds would give you '34' - because you "remove" the W: splitting-characters are never kept.

Potential fix:

import re

def dms2dd(s):
    degrees, minutes, seconds, *_ = re.split('[A-Z-]+', s)
    direction = s[-1]

    dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60)
    if direction in ('S','W'):
        dd*= -1
    return dd


print(dms2dd("18-23-34W"))  # -18.392777777777777  - add a round(_,6) to get yours
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69