[Python] Polars extract_all get the last item

Discussão em 'Python' iniciado por Stack, Maio 6, 2025.

  1. Stack

    Stack Membro Participativo

    so this works in polars

    path = ['some text 2020', '2021 text 2020', 'etxt 2022', '2023 text 2022']
    names = ["Alice", "Bob", "Charlie", "David"]

    # Create a Polars DataFrame with columns 'year' and 'name'
    df = pl.DataFrame({
    "path": path,
    "name": names
    })

    df

    year = ['2019', '2020', '2021', '2022', '2023']
    pattern = "((?i)" + '|'.join(year) + ")"
    df_new = df_new.with_columns(pl.col('path').str.extract(pattern).alias('series'))


    But now I want to extract_all and get the last item from the list it returns. This is not working.

    year = ['2019', '2020', '2021', '2022', '2023']
    pattern = "((?i)" + '|'.join(year) + ")"
    df_new = df_new.with_columns(pl.col('path').str.extract_all(pattern).arr.last()).alias('year')


    error

    SchemaError: invalid series dtype: expected `FixedSizeList`, got `list[str]`


    What am I doing wrong? Is .arr.last() wrong?

    Continue reading...

Compartilhe esta Página