1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Repeating a date in polars and exploding it

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

  1. Stack

    Stack Membro Participativo

    I have a polars dataframe with two date columns that represent a start and end date and then a value that I want to repeat for all dates in between those two dates so that I can join those on other tables.

    Example input is

    df = pl.from_repr("""
    ┌─────┬─────────────────────┬─────────────────────┬───────┐
    │ id ┆ start ┆ end ┆ value │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ datetime[ns] ┆ datetime[ns] ┆ i64 │
    ╞═════╪═════════════════════╪═════════════════════╪═══════╡
    │ 123 ┆ 2022-01-01 00:00:00 ┆ 2022-01-04 00:00:00 ┆ 10 │
    │ abc ┆ 2022-03-04 00:00:00 ┆ 2022-03-04 00:00:00 ┆ 3 │
    │ 456 ┆ 2022-05-11 00:00:00 ┆ 2022-05-16 00:00:00 ┆ 4 │
    └─────┴─────────────────────┴─────────────────────┴───────┘
    """)


    and expected output is

    shape: (11, 3)
    ┌─────┬─────────────────────┬───────┐
    │ id ┆ date ┆ value │
    │ --- ┆ --- ┆ --- │
    │ str ┆ datetime[ns] ┆ i64 │
    ╞═════╪═════════════════════╪═══════╡
    │ 123 ┆ 2022-01-01 00:00:00 ┆ 10 │
    │ 123 ┆ 2022-01-02 00:00:00 ┆ 10 │
    │ 123 ┆ 2022-01-03 00:00:00 ┆ 10 │
    │ 123 ┆ 2022-01-04 00:00:00 ┆ 10 │
    │ abc ┆ 2022-03-04 00:00:00 ┆ 3 │
    │ 456 ┆ 2022-05-11 00:00:00 ┆ 4 │
    │ 456 ┆ 2022-05-12 00:00:00 ┆ 4 │
    │ 456 ┆ 2022-05-13 00:00:00 ┆ 4 │
    │ 456 ┆ 2022-05-14 00:00:00 ┆ 4 │
    │ 456 ┆ 2022-05-15 00:00:00 ┆ 4 │
    │ 456 ┆ 2022-05-16 00:00:00 ┆ 4 │
    └─────┴─────────────────────┴───────┘

    Continue reading...

Compartilhe esta Página