Data_Sighentist
Data_Sighentist

Reputation: 29

How to Convert Latitude and Longitude by iterating through each row in DataFrame?

My DataFrame looks like this:

        latitude     longitude
0     40°02.894'N  105°18.006'W
1     40°02.894'N  105°18.006'W
2     40°02.894'N  105°18.006'W
3     40°02.894'N  105°18.006'W
4     40°02.894'N  105°18.006'W
...           ...           ...
5947  39°56.275'N  105°15.395'W
5948  39°56.275'N  105°15.395'W
5949  39°56.275'N  105°15.395'W
5950  39°56.275'N  105°15.395'W
5951  39°56.275'N  105°15.395'W

I am trying to iterate through each row to convert the degrees minutes seconds coordinate form to decimal degrees with something to the effect of:

 deg, minutes, seconds, direction =  re.split('[°\'."]', dataset['latitude'].astype(str))
(float(deg) + float(minutes)/60 + float(seconds)/(3600)) * (-1 if direction in ['W', 'S'] else 1)

and I get the error:

    229     and the remainder of the string is returned as the final element
    230     of the list."""
--> 231     return _compile(pattern, flags).split(string, maxsplit)
    232 
    233 def findall(pattern, string, flags=0):

TypeError: expected string or bytes-like object

I've tried all kinds of things through google, creating a function/for loop, and still cannot get this to spit out what I want. The output should look like 40.02894, -105.18006 after the math in conversion

Update: tried one of the variations submitted below:

for deg, minutes, seconds, direction in map(
    lambda x: re.split('[°\'."]',x), dataset['latitude'].astype(str)
    ):
    var1 = (float(deg) + float(minutes)/60 + float(seconds)/(3600))
    var2 = -1 if direction in ['W', 'S'] else 1
    result = var1 * var2

and returned:

----> 148 for deg, minutes, seconds, direction in map(
      149     lambda x: re.split('[°\'."]',x), dataset['latitude']
      150     ):
      151     var1 = (float(deg) + float(minutes)/60 + float(seconds)/(3600))

TypeError: 'DataFrame' object is not callable

Upvotes: 1

Views: 149

Answers (1)

Alexander
Alexander

Reputation: 17355

The reason you are getting the error is because the second argument of re.split should be a string or bytes like object and you are passing a pandas series.

try something like this instead:

for deg, minutes, seconds, direction in map(
    lambda x: re.split('[°\'."]',x), dataset['latitude']
    ):
    var1 = (float(deg) + float(minutes)/60 + float(seconds)/(3600))
    var2 = -1 if direction in ['W', 'S'] else 1
    print(var1 * var2)

Upvotes: 1

Related Questions