pythondataframepython-polars

dictionary to "long" dataframe


Is it possible to take a dictionary and transform it into a "long" dataframe in polars? basically have input that looks like

input_ = {"a": 1, "b": 2, "c": 3}

and I want output like

┌───────┬───────┐
│ col_0 ┆ col_1 │
│ ---   ┆ ---   │
│ str   ┆ i64   │
╞═══════╪═══════╡
│ a     ┆ 1     │
│ b     ┆ 2     │
│ c     ┆ 3     │
└───────┴───────┘

With pandas I use:

pd.DataFrame.from_dict(input_, orient="index").reset_index()

Solution

  • One option is to make a list of the items, then construct your DataFrame :

    input_ = {"a": 1, "b": 2, "c": 3} #`input` is a reserved built-in
    ​
    df = pl.DataFrame(list(input_.items()), schema=["col_0", "col_1"])
    

    Ouptut :

    print(df)
    ​
    shape: (3, 2)
    ┌───────┬───────┐
    │ col_0 ┆ col_1 │
    │ ---   ┆ ---   │
    │ str   ┆ i64   │
    ╞═══════╪═══════╡
    │ a     ┆ 1     │
    │ b     ┆ 2     │
    │ c     ┆ 3     │
    └───────┴───────┘