How to use ast.literal_eval in a pandas dataframe and handle exceptions

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))   

Leave a Comment