Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
Vaibhav Saxena Avatar asked Jul 30 '26 23:07

Vaibhav Saxena


1 Answers

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)
like image 74
ExplodingGayFish Avatar answered Aug 02 '26 13:08

ExplodingGayFish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!