[Python] How do join/map a polars dataframe to a dict?

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

  1. Stack

    Stack Membro Participativo

    I have a polars dataframe, and a dictionary. I want to map a column in the dataframe to the keys of the dictionary, and then add the corresponding values as a new column.

    import polars as pl

    my_dict = {
    'a': 1,
    'b': 2,
    }

    my_df = pl.DataFrame({'region': ['a', 'b', 'a']})


    ┌────────┐
    │ region │
    │ --- │
    │ str │
    ╞════════╡
    │ a │
    │ b │
    │ a │
    └────────┘


    I want to end up with:

    pl.DataFrame({'region': ['a', 'b', 'a'], 'city': [1, 2, 1]})


    ┌────────┬──────┐
    │ region ┆ city │
    │ --- ┆ --- │
    │ str ┆ i64 │
    ╞════════╪══════╡
    │ a ┆ 1 │
    │ b ┆ 2 │
    │ a ┆ 1 │
    └────────┴──────┘


    How can I do this?

    Continue reading...

Compartilhe esta Página