Ricardo Gomes
Ricardo Gomes

Reputation: 261

how to convert a string to a list in a dataframe column on python?

I have a df with the vertices coordinates of polygons. I imported that file and the coordinates are strings. How can I convert those to lists? So the "writing" should be the same but instead of being a string it should be a list of points.

import pandas as pd
df = pd.DataFrame()
data = {'Name': ['B1000', 'B1001', 'B1002'], 'Coordinates': ['[[[-9.124,38.714],[-9.124,38.714],[-9.1231966,38.713],[-9.122,38.7136]]]', '[[[-9.122,38.714],[-9.123,38.713],[-9.1231966,38.713],[-9.122,38.7136]]]', '[[[-9.165,38.740],[-9.165,38.740],[-9.1231966,38.713],[-9.1222,38.7136]]]']}
df = pd.DataFrame(data) 

    Name    coordinates
0   B1000   [[[-9.124,38.714],[-9.124,38.714],[-9.1231966,38.713],[-9.122,38.7136]]]
1   B1001   [[[-9.122,38.714],[-9.123,38.713],[-9.1231966,38.713],[-9.122,38.7136]]]
2   B1002   [[[-9.165,38.740],[-9.165,38.740],[-9.1231966,38.713],[-9.1222,38.7136]]]

# now I have this:
type(df['Coordinates'][0])
str

Upvotes: 2

Views: 48

Answers (1)

RunTheGauntlet
RunTheGauntlet

Reputation: 302

Alternatively, you could use eval function without using additional modules:

df['Coordinates'] = df['Coordinates'].apply(lambda s: eval(s))

type(df['coordinates'][0])
list

Upvotes: 1

Related Questions