Vaibhav Saxena
Vaibhav Saxena

Reputation: 67

Convert a column in a dataframe from type string to tuple

I have a dataframe 'data' which has a column 'city' that appears to be a tuple. However, when I try to access its element, it comes out to be in string. As shown below:

data.city[0]

The output is:

"(0, ['New York', 'Delhi', 'Bangkok'])"

Apparently, all the items are in string format.

I want the output as follows:

(0, ['New York', 'Delhi', 'Bangkok'])

How can I achieve this?

Upvotes: 3

Views: 5693

Answers (2)

Partha Mandal
Partha Mandal

Reputation: 1441

Use ast.literal_eval. Although it can throw exceptions if you have an empty string. So, wrapping that in a str function should be prudent:

from ast import literal_eval
df['city'] = df.city.apply(lambda x: literal_eval(str(x)))

Upvotes: 2

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

You can use ast.literal_eval

import ast
x = ast.literal_eval("(0, ['New York', 'Delhi', 'Bangkok'])")
print(x)
print(type(x))

Output:

(0, ['New York', 'Delhi', 'Bangkok'])
<class 'tuple'>

In your case, you can use:

data.city = data.city.apply(ast.literal_eval)

Upvotes: 8

Related Questions