In Polars, the rows() method converts a DataFrame into native Python data structures. By default, it returns a list of tuples, with each tuple representing a row in the DataFrame. If named=True is passed, it returns a list of dictionaries instead, using column names as keys.
In this article, I will explain the Polars DataFrame rows() method, covering its syntax, parameters, and usage. This method returns all rows from the DataFrame as either a list of tuples or a list of dictionaries, depending on the parameter you specify.
Key Points –
rows()returns all rows of a DataFrame as a list of tuples by default.- By default, outputs a list of tuples, each tuple representing a row.
- The values in each tuple are ordered according to the DataFrame’s column order.
- When used with
named=True, returns a list of dictionaries with column names as keys. rows(named=True)returns rows as a list of dictionaries instead of tuples.- The
rows()method allows easy iteration over DataFrame rows in Python. rows()is useful for exporting or transforming data into native Python structures.- Using
rows(named=True)is ideal when you need to reference values by column names for clarity.
<a id="h-polars-dataframe-rows-introduction"></a>
Polars DataFrame rows() Introduction
Let’s know the syntax of the DataFrame rows() function
# Syntax of DataFrame rows()
DataFrame.rows(
*,
named: bool = False,
) → list[tuple[Any, ...]] | list[dict[str, Any]]
<a id="h-parameters-of-the-dataframe-rows"></a>
Parameters of the DataFrame rows()
Following are the parameters of the DataFrame rows() function
named: bool = False(optional keyword-only argument)- If
False(default), returns a list of tuples (each tuple is a row). - If
True, returns a list of dictionaries (each dict maps column names to row values).
- If
<a id="h-return-value"></a>
Return Value
This function returns a list of tuples, where each tuple represents a row in the DataFrame.
<a id="h-usage-of-polars-dataframe-rows-method"></a>
Usage of Polars DataFrame rows() Method
It returns all rows of the DataFrame as either a list of tuples or a list of dictionaries, depending on the named parameter.
Now, let’s create a Polars DataFrame.
import polars as pl
technologies= {
'Courses':["Spark","PySpark","Hadoop","Python"],
'Fees' :[22000,25000,23000,24000],
'Duration':['30days','50days','60days','40days'],
'Discount':[1000,2000,1200,2500]
}
df = pl.DataFrame(technologies)
print("Original DataFrame:\n", df)
Yields below output.
To retrieve the rows of your Polars DataFrame as a list of tuples (the default output of the rows() method), simply call rows() on your DataFrame.
# Get rows as list of tuples
rows_list = df.rows()
print(rows_list)
In the above example, each tuple in the list represents a row of the DataFrame, with values in the order of columns: Courses, Fees, Duration, Discount.
<a id="h-get-rows-as-a-list-of-dictionaries-named-true"></a>
Get Rows as a List of Dictionaries (Named=True)
To retrieve the rows of a Polars DataFrame as a list of dictionaries, use the rows(named=True) method. Each row will be represented as a dictionary, with column names as keys and the corresponding values as dictionary values.
# Get rows as a list of dictionaries
rows_as_dicts = df.rows(named=True)
print(rows_as_dicts)
# Output:
# [
# {'Courses': 'Spark', 'Fees': 22000, 'Duration': '30days', 'Discount': 1000},
# {'Courses': 'PySpark', 'Fees': 25000, 'Duration': '50days', 'Discount': 2000},
# {'Courses': 'Hadoop', 'Fees': 23000, 'Duration': '60days', 'Discount': 1200},
# {'Courses': 'Python', 'Fees': 24000, 'Duration': '40days', 'Discount': 2500}
# ]
In the above example, rows() returns a list of tuples, while rows(named=True) returns a list of dictionaries where column names serve as keys, handy when you need named access to each value.
<a id="h-iterate-over-rows-as-tuples"></a>
Iterate Over Rows as Tuples
To iterate over rows as tuples in a Polars DataFrame, use a for loop in combination with the rows() method.
# Iterate over rows as tuples
for row in df.rows():
print
# Output:
# ('Spark', 22000, '30days', 1000)
# ('PySpark', 25000, '50days', 2000)
# ('Hadoop', 23000, '60days', 1200)
# ('Python', 24000, '40days', 2500)
In the above example, Each row is a Python tuple, with values in the same order as the columns in the DataFrame.
<a id="h-iterate-over-rows-as-dictionaries"></a>
Iterate Over Rows as Dictionaries
To iterate over rows as dictionaries in a Polars DataFrame, use the rows(named=True) method within a loop. This returns each row as a dictionary where the keys are the column names.
# Iterate over rows as dictionaries
for row_dict in df.rows(named=True):
print(row_dict)
# Output:
# {'Courses': 'Spark', 'Fees': 22000, 'Duration': '30days', 'Discount': 1000}
# {'Courses': 'PySpark', 'Fees': 25000, 'Duration': '50days', 'Discount': 2000}
# {'Courses': 'Hadoop', 'Fees': 23000, 'Duration': '60days', 'Discount': 1200}
# {'Courses': 'Python', 'Fees': 24000, 'Duration': '40days', 'Discount': 2500}
In the above example, each row_dict is a dictionary where keys are column names and values are the row values. Perfect for more readable or key-based access inside your loop.
<a id="h-access-first-row-tuple"></a>
Access First Row Tuple
To access the first row as a tuple from a Polars DataFrame, you can use the rows() method and then index the first element [0].
# Get the first row as a tuple
df2 = df.rows()[0]
print(df2)
# Output:
# ('Spark', 22000, '30days', 1000)
In the above example, this returns the first row as a tuple with all column values in order.
<a id="h-access-first-row-as-dict"></a>
Access First Row as Dict
To access the first row as a dictionary in a Polars DataFrame, call rows(named=True) and retrieve the first element [0] from the resulting list.
# Get the first row as a dictionary
df2 = df.rows(named=True)[0]
print(df2)
# Output:
# {'Courses': 'Spark', 'Fees': 22000, 'Duration': '30days', 'Discount': 1000}
In the above example, this gives you the first row with column names as keys and the corresponding values.
<a id="h-conclusion"></a>
Conclusion
In summary, Polars provides flexible methods to access DataFrame rows, whether as tuples using rows() or as dictionaries with rows(named=True). These options make it easy to iterate over and manipulate data in the format that best suits your needs.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars DataFrame Drop Nans
- Polars Adding Days to a Date
- Replace Value by Null in Polars
- Add Row of Column Totals in Polars
- Polars DataFrame Columns Selection
- How to use isin in Polars DataFrame?
- Polars Delete a Column from DataFrame
- Polars String Manipulation of Cell Contents
- Polars String Concatenation of Two Existing Columns
- How to Get the Name of an Aliased Expression in Polars?
- Polars DataFrame with_columns() Function with Examples
- How to Change the First Letter of the Column Name to Uppercase in Polars?
<a id="h-reference"></a>
