Polars Row object to Dictionary

Question:

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?

Asked By: Chris

||

Answers:

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}
Answered By: glebcom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.