[Python] Construct date column from year, month and day in Polars dataframe

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    Consider the following Polars dataframe:


    df = pl.DataFrame({
    'date': ['2022-01-01', '2022-02-01', '2022-03-01']
    })

    df.with_column(pl.col('date').str.strptime(pl.Date, fmt='%Y-%m').cast(pl.Datetime)).alias('year-month')



    Currently the dataframe is:

    date
    2022-01-01
    2022-02-01
    2022-03-01

    The desired output is:

    date year-month
    2022-01-01 2022-01
    2022-02-01 2022-02
    2022-03-01 2022-03

    I have tried:


    df.with_column(pl.col('date').str.strptime(pl.Date, fmt='%Y-%m').cast(pl.Datetime)).alias('year-month')



    I get:

    SchemaError: invalid series dtype: expected Utf8, got datetime[ns]

    Thanks so much!!!

    Continue reading...

Compartilhe esta Página