1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Pure polars version of safe ast literal eval

Discussão em 'Python' iniciado por Stack, Outubro 4, 2024 às 00:22.

  1. Stack

    Stack Membro Participativo

    I have data like this,

    df = pl.DataFrame({'a': ["['b', 'c', 'd']"]})


    I want to convert the string to a list I use,

    df = df.with_columns(a=pl.col('a').str.json_decode())


    it gives me,

    ComputeError: error inferring JSON: InternalError(TapeError) at character 1 (''')


    then I use this function,

    import ast
    def safe_literal_eval(val):
    try:
    return ast.literal_eval(val)
    except (ValueError, SyntaxError):
    return val
    df = df.with_columns(a=pl.col('a').map_elements(safe_literal_eval, return_dtype=pl.List(pl.String)))


    and get the expected output, but is there a pure polars way to achieve the same?

    Continue reading...

Compartilhe esta Página