Extract from column only the digits and split to different columns

I have used regex match for efficient extraction of latitudes and longitudes. This can obtained using following code.

import re
import pandas as pd

df = pd.DataFrame({
    'ID': [341,321],
    'name':['Dali','daLi'],
    'year':[1995, 1996],
    'location':['{{"{\"latitude\":\"9.4714611480000004\",\"longitude\":\"4.3520187860000004\"}","{\"latitude\":\"9.4720611479999999\",\"longitude\":\"4.3520187860000004\"}}',
                '{{"{\"latitude\":\"9.4714611480000004\",\"longitude\":\"4.3520187860000004\"}","{\"latitude\":\"9.4720611479999999\",\"longitude\":\"4.3520187860000004\"}}']
})

Solution

df_new = df.location.apply(lambda x: re.findall(r"\d+\.*\d*",x))
df_new = pd.DataFrame(df_new.to_list(), columns=['lat1','long1','lat2','long2'])
pd.concat([df.iloc[:,0:3], df_new], axis=1)

output

    ID  name    year    lat1                long1               lat2                long2
0   341 Dali    1995    9.4714611480000004  4.3520187860000004  9.4720611479999999  4.3520187860000004
1   321 daLi    1996    9.4714611480000004  4.3520187860000004  9.4720611479999999  4.3520187860000004

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top