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

后端 未结 2 1579
不思量自难忘°
不思量自难忘° 2020-12-19 09:54

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

相关标签:
2条回答
  • 2020-12-19 10:33

    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
    
    0 讨论(0)
  • 2020-12-19 10:43

    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))   
    
    0 讨论(0)
提交回复
热议问题