Home > Software design >  Swap coordinates in Dataframe column
Swap coordinates in Dataframe column

Time:08-28

how is it possible to swap the coordinates in a pandas dataframe column (location) from (Lat,Lon) to (Lon,Lat)?

name                         location   
0   Plaza Botero            ( -75.5686261812429,6.2524857541249315) 
1   Universidad de Medellín ( -75.6116092592174,6.231704691813073)
2   Parque Juanes de la Paz ( -75.56945687270888,6.290384323934336)
3   Parque del Poblado      ( -75.57088108434691,6.210362095508166) 
4   Alcaldía de Medellín    ( -75.57371337731854,6.2451496127526225)    
5   Parque Explora          ( -75.56556245591827,6.271208962002754) 

Thanks!

CodePudding user response:

Considering that the values in the location colum are tuples, you can use this :

import pandas as pd

df = pd.DataFrame({'name': ['Plaza Botero', 'Universidad de Medellín', 'Parque Juanes de la Paz', 'Parque del Poblado', 
                           'Alcaldía de Medellín', 'Parque Explora'],
                  'location': [(-75.5686261812429,6.2524857541249315), (-75.6116092592174,6.231704691813073), 
                               (-75.56945687270888,6.290384323934336), (-75.57088108434691,6.210362095508166), 
                               (-75.57371337731854,6.2451496127526225), (-75.56556245591827,6.271208962002754)]})

df['location'] = [(t[1], t[0]) for t in df['location']]

>>> print(df)

enter image description here

CodePudding user response:

If you have tuples, use the str accessor with a reverse slice:

df['location'] = df['location'].str[::-1]

If you have strings, str.replace:

df['location'] = df['location'].str.replace(r'\(([^,] ),([^,] )\)',
                                            r'(\2,\1)', regex=True)

output:

                      name                                  location
0             Plaza Botero   (6.2524857541249315, -75.5686261812429)
1  Universidad de Medellín    (6.231704691813073, -75.6116092592174)
2  Parque Juanes de la Paz   (6.290384323934336, -75.56945687270888)
3       Parque del Poblado   (6.210362095508166, -75.57088108434691)
4     Alcaldía de Medellín  (6.2451496127526225, -75.57371337731854)
5           Parque Explora   (6.271208962002754, -75.56556245591827)

CodePudding user response:

This answer will work whether the locations are strings or tuples:

from ast import literal_eval
df.location.astype(str).agg(literal_eval).str[::-1]
  • Related