Amartin
Amartin

Reputation: 337

How to unlist a list with one value inside a pandas columns?

I have a pandas data frame:

Id       Col1
1     ['string']
2     ['string2']

Is possible to convert the data frame into another data frame that look like this?

Id     Col1
1     string
2     string2

I tried with this way but only get the [.

df.col1.apply(lambda x: x[0])

Thanks for your time!

Upvotes: 2

Views: 1679

Answers (1)

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

I tried with this way but only get the [.

Then this means they are strings, not lists. You can convert them to lists by applying ast.literal_eval and then explode:

import ast

df.Col1 = df.Col1.apply(ast.literal_eval).explode()

to get

   Id     Col1
0   1   string
1   2  string2

Upvotes: 5

Related Questions