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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With