Polars行对象转为字典

huangapple go评论76阅读模式
英文:

Polars Row object to Dictionary

问题

I'm trying to iterate through the rows of a Polars DataFrame, where the iterator returns a dictionary of each row.

The documentation indicates that iter_rows(named=True) is what I want. However, I get an "AttributeError: 'DataFrame' object has no attribute 'iter_rows'" error when I try to use it.

iterrows(named=True) without the underscore does seem to mostly work, but it is returning a Polars Row object rather than a dictionary. I can access the value using either integer indexes or dot notation with the column name, but it's not clear how I can get the column name / key.

import polars as pl

df = pl.DataFrame({
    'a': [1, 2, 3],
    'b': [4, 5, 6]
})
for row in df.iterrows(named=True):
    print(type(row))
    print(row[0])
    print(row.a)

Is it possible to either get the column name / key values from the Row object or otherwise change it to a Python dictionary?

英文:

I'm trying to iterate through the rows of a Polars DataFrame, where the iterator returns a dictionary of each row.

The documentation indicates that iter_rows(named=True) is what I want. However, I get an "AttributeError: 'DataFrame' object has no attribute 'iter_rows'" error when I try to use it.

iterrows(named=True) without the underscore does seem to mostly work, but it is returning a Polars Row object rather than a dictionary. I can access the value using either integer indexes or dot notation with the column name, but it's not clear how I can get the column name / key.

import polars as pl

df = pl.DataFrame({
    'a': [1, 2, 3],
    'b': [4, 5, 6]
})
for row in df.iterrows(named=True):
    print(type(row))
    print(row[0])
    print(row.a)

Is it possible to either get the column name / key values from the Row object or otherwise change it to a Python dictionary?

答案1

得分: 0

for `polars=0.16.11`:

```python
for row in df.iter_rows(named=True):
    print(row)
{'a': 1, 'b': 4}
{'a': 2, 'b': 5}
{'a': 3, 'b': 6}
英文:

for polars=0.16.11:

for row in df.iter_rows(named=True):
    print(row)
{'a': 1, 'b': 4}
{'a': 2, 'b': 5}
{'a': 3, 'b': 6}

huangapple
  • 本文由 发表于 2023年3月7日 00:44:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定