Polars行对象转为字典

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

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.

  1. import polars as pl
  2. df = pl.DataFrame({
  3. 'a': [1, 2, 3],
  4. 'b': [4, 5, 6]
  5. })
  6. for row in df.iterrows(named=True):
  7. print(type(row))
  8. print(row[0])
  9. 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.

  1. import polars as pl
  2. df = pl.DataFrame({
  3. 'a': [1, 2, 3],
  4. 'b': [4, 5, 6]
  5. })
  6. for row in df.iterrows(named=True):
  7. print(type(row))
  8. print(row[0])
  9. 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

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

for polars=0.16.11:

  1. for row in df.iter_rows(named=True):
  2. print(row)
  1. {'a': 1, 'b': 4}
  2. {'a': 2, 'b': 5}
  3. {'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:

确定