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

将Polars DataFrame两列转为指定字典时遇TypeError问题求助

解决Polars DataFrame转字典时的TypeError问题

错误原因

你的代码中polar_df.select(pl.col('foo'))和polar_df.select(pl.col('bar'))返回的是Polars DataFrame对象,而Python字典的键必须是可哈希类型(如字符串、数字),但DataFrame/Series属于不可哈希的容器类型,因此抛出TypeError: unhashable type: 'Series'。

另外原代码创建DataFrame时缺少外层大括号,这也是语法错误,需要先修正。

正确解法

解法1:提取原生Python列表构造字典

直接将Polars Series转换为Python原生列表,再用dict(zip(...))构造目标字典:

import polars as pl

# 修正语法错误,正确创建DataFrame
polar_df = pl.DataFrame({
    "foo": ['a', 'b', 'c'],
    "bar": [[6.0, 7.0, 8.0],[9.0,10.0,11.0],[12.0,13.0,14.0]]
})

# 转换为目标字典
dict_output = dict(zip(polar_df['foo'].to_list(), polar_df['bar'].to_list()))
print(dict_output)
# 输出: {'a': [6.0, 7.0, 8.0], 'b': [9.0, 10.0, 11.0], 'c': [12.0, 13.0, 14.0]}

解法2:利用Polars内置方法(更简洁)

通过设置索引后调用to_dict(),一步得到结果:

import polars as pl

polar_df = pl.DataFrame({
    "foo": ['a', 'b', 'c'],
    "bar": [[6.0, 7.0, 8.0],[9.0,10.0,11.0],[12.0,13.0,14.0]]
})

dict_output = polar_df.set_index('foo')['bar'].to_dict()
print(dict_output)
# 输出与上述一致

内容的提问来源于stack exchange,提问作者Rakesh Chaudhary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:22:50