I have a dataframe
with a column containing a tuple
data as a string. Eg. \'(5,6)\'
. I need to convert this to a tuple structure. One
This works when the function is changed to:
def literal_return(val):
try:
return ast.literal_eval(val)
except (ValueError, SyntaxError) as e:
return val
I would do it simply requiring a string type from each entry:
from ast import literal_eval
df['column_2'] = df.column_1.apply(lambda x: literal_eval(str(x)))
If You need to advanced Exception handling, You could do, for example:
def f(x):
try:
return literal_eval(str(x))
except Exception as e:
print(e)
return []
df['column_2'] = df.column_1.apply(lambda x: f(x))