Chinmay
Chinmay

Reputation: 145

Strip column data based on several delimiters

I have elevation data from Google Maps api which outputs a dataframe like this.

  elevation                              location 
0  996.330994   {'lat': 32.1897, 'lng': -103.18327}    
1  995.314880   {'lat': 32.1894, 'lng': -103.18237}    
2  994.983276  {'lat': 32.18729, 'lng': -103.18365}    
3  995.970520   {'lat': 32.18416, 'lng': -103.1822}    
4  997.625549  {'lat': 32.19115, 'lng': -103.18418}   

I want to strip the location column into two separate columns with latitude and longitude

I tried doing

df['location'] =df['location'].astype('str')

df['location'] =df['location'].str.strip('{}')

It returns me

  elevation                              location 
0  996.330994   'lat': 32.1897, 'lng': -103.18327    
1  995.314880   'lat': 32.1894, 'lng': -103.18237    
2  994.983276   'lat': 32.18729,'lng': -103.18365    
3  995.970520   'lat': 32.18416,'lng': -103.1822    
4  997.625549   'lat': 32.19115,'lng': -103.18418   

Couldn't go ahead of this.

Upvotes: 0

Views: 45

Answers (2)

Vaishali
Vaishali

Reputation: 38415

Give that the values in location are dictionaries, try

df[['lat', 'lng']] = df.location.apply(pd.Series)

    elevation   location                               lat      lng
0   996.330994  {'lat': 32.1897, 'lng': -103.18327}    32.18970 -103.18327
1   995.314880  {'lat': 32.1894, 'lng': -103.18237}    32.18940 -103.18237
2   994.983276  {'lat': 32.18729, 'lng': -103.18365}   32.18729 -103.18365
3   995.970520  {'lat': 32.18416, 'lng': -103.1822}    32.1841  -103.18220
4   997.625549  {'lat': 32.19115, 'lng': -103.18418}   32.19115 -103.18418

Upvotes: 1

BENY
BENY

Reputation: 323306

Using concat after reconstruct your dict type columns

pd.concat([df,pd.DataFrame(df.location.tolist(),index=df.index)],axis=1)
Out[234]: 
   elevation                             location      lat        lng
0          1  {'lat': 32.1897, 'lng': -103.18327}  32.1897 -103.18327
1          2  {'lat': 32.1894, 'lng': -103.18237}  32.1894 -103.18237

Upvotes: 2

Related Questions