将 Polars 数据帧的 2 列转换为字典,其键作为第一列元素,第二列元素作为值

Rak*_*ary 7 python-polars

我正在使用下面的数据框转换为特定格式的字典。

但是,我收到错误 TypeError: unhashable type: 'Series'

import polars as pl

#input (polars eager 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]]
)

#expected output (dictionary):
#{'a':[6.0, 7.0, 8.0],'b':[9.0,10.0,11.0],'c':[12.0,13.0,14.0]}

dict_output = 
dict(zip(polar_df.select(pl.col('foo')),
polar_df.select(pl.col('bar'))
))
Run Code Online (Sandbox Code Playgroud)

jqu*_*ous 8

做到这一点的“极地方式”是dict()+.iter_rows()

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]]
})
Run Code Online (Sandbox Code Playgroud)
>>> dict(df.iter_rows())
{'a': [6.0, 7.0, 8.0], 'b': [9.0, 10.0, 11.0], 'c': [12.0, 13.0, 14.0]}
Run Code Online (Sandbox Code Playgroud)