Change values in dictionary out of dataframe

Viewed 35

i have a dataframe like this

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) 

and a route dictionary like this:

routes= {0: [0, 1, 0], 1: [0, 2, 3, 0], 2: [0, 5, 4, 0]}

how can I create a new dictionary with the coordinates instead of the indexes?

e.g. for Route 0:

route_0= {0:[( -75.5686261812429,6.2524857541249315),( -75.6116092592174,6.231704691813073),( -75.5686261812429,6.2524857541249315)}

instead of 0 in the list the coordinates (-75.5686261812429,6.2524857541249315)

Thanks a lot

1 Answers

Try:

# convert `location` column to python tuples (skip this if they are tuples already):
from ast import literal_eval
df["location"] = df["location"].apply(literal_eval)

routes = {0: [0, 1, 0], 1: [0, 2, 3, 0], 2: [0, 5, 4, 0]}

x = pd.Series(routes).explode()
out = df.loc[x, "location"].groupby(x.index).agg(list).to_dict()
print(out)

Prints:

{
    0: [
        (-75.5686261812429, 6.2524857541249315),
        (-75.6116092592174, 6.231704691813073),
        (-75.5686261812429, 6.2524857541249315),
    ],
    1: [
        (-75.5686261812429, 6.2524857541249315),
        (-75.56945687270888, 6.290384323934336),
        (-75.57088108434691, 6.210362095508166),
        (-75.5686261812429, 6.2524857541249315),
    ],
    2: [
        (-75.5686261812429, 6.2524857541249315),
        (-75.56556245591827, 6.271208962002754),
        (-75.57371337731854, 6.2451496127526225),
        (-75.5686261812429, 6.2524857541249315),
    ],
}
Related