0

I have a dataframe df like these 3 first rows are these

City Longitude Latitude
Toluca W099.6569 N19.2925
Pune E73.8562 N18.5167
Bloemfontain E026.216667 S29.116667

For example Bloemfontain row should be like these at the end

City Longitude Latitude
Bloemfontain -29.116667 26.216667

I used this code

pattern = r'(?P<d>[\d\.]+).*?(?P<m>[\d\.]+).*?(?P<s>[\d\.]+)'
dms = df['Latitude'].str.extract(pattern).astype(float)
df['LATITUDE'] = dms['d'] + dms['m'].div(60) + dms['s'].div(3600)
dms = df['Longitude'].str.extract(pattern).astype(float)
df['LONGITUDE'] = dms['d'] + dms['m'].div(60) + dms['s'].div(3600)

but got not the right longitude and latitude

6
  • What type of object is latitude and longitude? Can you do this and tell me what it prints: print(type(df['Latitude'])). Is it a string?
    – ss3387
    Oct 31, 2022 at 18:57
  • <class 'pandas.core.series.Series'>
    – user20374625
    Oct 31, 2022 at 19:00
  • ok now try printing this: type(df['Latitude'].str)
    – ss3387
    Oct 31, 2022 at 19:03
  • pandas.core.strings.accessor.StringMethods
    – user20374625
    Oct 31, 2022 at 19:04
  • Your pattern seems to be expecting the geographic coordinates in degrees, minutes and seconds but such inputs are not indicated anywhere in your question.
    – radof
    Oct 31, 2022 at 19:25

1 Answer 1

0

I don't see where it is necessary to utilize a pattern search at all. Here is how I would do the task.

# function to perform the partitioning
def cnvrtCoord(val: str) -> float:
    sgn = +1
    if val[0] == 'S' or val[0] == 'W':
        sgn = -1
    return float(val[1:]) * sgn  

Then to change the contents of the Longitude and Latitude columns use:

df['Longitude'] = [cnvrtCoord(x) for x in df['Longitude'].tolist()]
df['Latitude'] = [cnvrtCoord(x) for x in df['Latitude'].tolist()]  

This would produce the dataframe shown below given your input sample:

    City    Longitude   Latitude
0   Toluca  -99.656900  19.292500
1   Pune    73.856200   18.516700
2   Bloemfontain    26.216667   -29.116667

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.