英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论