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] Python Polars join on column with greater or equal

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

  1. Stack

    Stack Membro Participativo

    I have two polars dataframe, one dataframe df_1 with two columns start and end the other dataframe df_2 one with a column dates and I want to do a left join on df_2 under the condition that the dates column is in between the start and end column.

    To make it more obvious what I want to do here is an example

    DATA

    import polars as pl
    from datetime import date

    df_1 = pl.DataFrame(
    {
    "id": ["abc", "abc", "456"],
    "start": [date(2022, 1, 1), date(2022, 3, 4), date(2022, 5, 11)],
    "end": [date(2022, 2, 4), date(2022, 3, 10), date(2022, 5, 16)],
    "value": [10, 3, 4]

    }
    )

    df_2 = pl.DataFrame(
    {
    "id": ["abc", "abc", "456", "abc", "abc", "456"],
    "dates": [date(2022, 1, 2), date(2022, 3, 4), date(2022, 5, 11), date(2022, 1, 4), date(2022, 3, 7), date(2022, 5, 13)],
    }
    )


    So now I would join on id and that dates is in between start and end and the result should look like that

    RESULT

    shape: (6, 3)
    ┌─────┬────────────┬───────┐
    │ id ┆ dates ┆ value │
    │ --- ┆ --- ┆ --- │
    │ str ┆ date ┆ i64 │
    ╞═════╪════════════╪═══════╡
    │ abc ┆ 2022-01-02 ┆ 10 │
    │ abc ┆ 2022-03-04 ┆ 3 │
    │ 456 ┆ 2022-05-11 ┆ 4 │
    │ abc ┆ 2022-01-04 ┆ 10 │
    │ abc ┆ 2022-03-07 ┆ 3 │
    │ 456 ┆ 2022-05-13 ┆ 4 │
    └─────┴────────────┴───────┘

    Continue reading...

Compartilhe esta Página