Splitting latlong into lat and long

Viewed 64

I'm trying to remove the square brackets from a list of latlongs called latlng, which is held in a dataframe (df) in the format as per example below:

        latlng
[-1.4253128, 52.9015902]

I've got this but it returns NaN:

df['latitude'] = df['latlng'].str.replace('[','')

and produces this warning:

<ipython-input-59-34b588ef7f4b>:1: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will*not* be treated as literal strings when regex=True.
  df['latitude'] = df['latlng'].str.replace('[','')

It seems that if I write the file to a csv and then use that file, the above works. But ideally, I want it all in once script. Any help is appreciated!

2 Answers

I think you meant to write df['latitude'] = str(df['latlng']).replace('[','').

Yet, this only removes the opening bracket and will not return long or lat alone.

You might want to use regex to split the string, something on the lines such as

import re

splitted = re.match("\[(-?\d+\.\d+),\s*(-?\d+\.\d+)\]", "[-1.4253128, 52.9015902]")
print(splitted[1])
print(splitted[2])

Use indices:

df['latitude'] = df['latlng'].str[0]
df['longitude'] = df['latlng'].str[1]

Even if they are objects, str[] accessor allows access to their values.

Related