You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Polars中将字典转换为长格式DataFrame?

在Polars中将字典转换为长格式DataFrame的方法

当然可以在Polars中实现字典到长格式DataFrame的转换,以下是两种简洁的实现方式,对应你给出的输入和期望输出:

方法一:直接利用字典的items()构造DataFrame

这是最直接的方式,将字典的键值对作为行数据传入pl.DataFrame,同时指定列名:

import polars as pl

input_ = {"a": 1, "b": 2, "c": 3}
df = pl.DataFrame(input_.items(), schema=["col_0", "col_1"])

执行后得到的DataFrame与你期望的格式完全一致:

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

方法二:先转宽表再熔化为长表

如果你习惯类似Pandas的思路,也可以先将字典转为宽格式DataFrame,再用melt方法转换为长格式:

import polars as pl

input_ = {"a": 1, "b": 2, "c": 3}
df = pl.DataFrame(input_).melt(variable_name="col_0", value_name="col_1")

这种方式同样能得到目标结果。

对比你使用的Pandas代码:

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

Polars的实现逻辑更直观,代码也更简洁。

内容的提问来源于stack exchange,提问作者dave-edison

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 08:54:55