In Polars, the row() function allows you to retrieve a specific row from a DataFrame as a tuple. This can be useful when you need to extract an individual record in a structured format. By default, the function returns rows as tuples, maintaining the column order. However, if named=True is specified, the row is returned as a dictionary with column names as keys.
In this article, I will explain the Polars DataFrame row() function, covering its syntax, parameters, and usage. I will also demonstrate how to retrieve a single row from a DataFrame as a tuple or dictionary. You can select the row either by index or using a predicate.
Key Points –
- Retrieves a single row from a Polars DataFrame as either a tuple or a dictionary.
- Supports index-based access by providing a zero-based integer index.
- Allows predicate-based selection using
by_predicate, which selects a row that meets a specific condition. - It returns a tuple by default, but the setting
named=Truereturns a dictionary with column names as keys. - If
by_predicateis used and matches multiple rows, an error is raised (it expects a single matching row). - Efficient for retrieving a single row, but for multiple rows,
rows()should be used instead. - Supports complex filtering expressions with
by_predicate, making it flexible for conditional row selection.
<a id="h-polars-dataframe-row-introduction"></a>
Polars DataFrame row() Introduction
Let’s know the syntax of the Polars DataFrame row() function.
# Syntax of Polars row()
DataFrame.row(
index: int | None = None,
*,
by_predicate: Expr | None = None,
named: bool = False,
) → tuple[Any, ...] | dict[str, Any]
<a id="h-parameters-of-the-polars-dataframe-row"></a>
Parameters of the Polars DataFrame.row()
Following are the parameters of the row() function.
index(int, optional) - The row index (0-based) to retrieve.by_predicate(Expr, optional) - Retrieves the first row where the condition evaluates to True.named(bool, default=False) - Returns a dictionary instead of a tuple if set to True.
<a id="h-return-value"></a>
Return Value
This function returns a tuple (tuple[Any, …]) when named=False (default) and a dictionary (dict[str, Any]) when named=True.
<a id="h-usage-of-polars-dataframe-row-function"></a>
Usage of Polars DataFrame row() Function
The row() function in Polars is used to retrieve a single row from a DataFrame, either by index or by applying a condition (predicate).
To run some examples of the Polars DataFrame row() function, let’s create a Polars DataFrame.
import polars as pl
technologies= ({
'Courses':["spark","python","pandas"],
'Fees' :[22000,25000,24000],
'Duration':['30days','60days','50days'],
'Discount':[1000,2000,2500]
})
df = pl.DataFrame(technologies)
print("Original DataFrame:\n", df)
Yields below output.
You can retrieve a row by its index using the row() function in Polars. By default, it returns the row as a tuple.
# Get the row at index 1 (second row)
df2 = df.row(1)
print("Row at index 1:\n", df2)
Here,
df.row(1)retrieves the second row (index1is zero-based).- The output is a tuple containing all column values from that row.
<a id="h-retrieve-a-row-by-index-with-named-output-dictionary"></a>
Retrieve a Row by Index with Named Output (Dictionary)
By default, the row() function in Polars returns a row as a tuple. However, if you want the output as a dictionary with column names, you can set named=True.
# Retrieve row at index 1 as a dictionary
df2 = df.row(1, named=True)
print("\nRow at index 1 (Named Output):\n", df2)
# Output:
# Row at index 1 (Named Output):
# {'Courses': 'python', 'Fees': 25000, 'Duration': '60days', 'Discount': 2000}
Here,
df.row(1, named=True)retrieves the second row (index 1 is zero-based).- The output is a dictionary, where keys are column names and values are row data.
<a id="h-retrieve-a-row-by-predicate"></a>
Retrieve a Row by Predicate
The row() function in Polars allows retrieving a row based on a condition (predicate) using the by_predicate parameter. This is useful when you want to extract the row that satisfies a certain condition.
# Retrieve the row where Courses == "pandas"
df2 = df.row(by_predicate=pl.col("Courses") == "pandas")
print("Row where Courses is 'python':\n", df2)
# Output:
# Row where Courses is 'python':
# ('pandas', 24000, '50days', 2500)
Here,
df.row(by_predicate=pl.col("Courses") == "pandas")filters the DataFrame for the row where "Courses" is"pandas".- The function returns a tuple with the values of the matching row.
- This method works only if exactly one row matches the condition.
<a id="h-retrieve-a-named-row-by-predicate"></a>
Retrieve a Named Row by Predicate
To retrieve a row using a predicate and return it as a dictionary (with column names as keys), use the by_predicate parameter along with named=True.
# Retrieve the row where Courses == "python" and return as a dictionary
df2 = df.row(by_predicate=pl.col("Courses") == "spark", named=True)
print("Named Row where Courses is 'python':\n", df2)
# Output:
# Named Row where Courses is 'python':
# {'Courses': 'spark', 'Fees': 22000, 'Duration': '30days', 'Discount': 1000}
Here,
df.row(by_predicate=pl.col("Courses") == "spark", named=True)retrieves the row where the"Courses"column equals"spark"and returns it as a dictionary, with column names as keys.- This method is useful when you need to work with key-value pairs instead of a tuple.
<a id="h-using-row-with-a-filtered-dataframe"></a>
Using row() with a Filtered DataFrame
You can first filter a Polars DataFrame and then use the row() function to retrieve a specific row from the filtered result.
# First, filter the DataFrame where Fees > 23000
filtered_df = df.filter(pl.col("Fees") > 23000)
# Retrieve the first row from the filtered DataFrame
df2 = filtered_df.row(0)
print("First row from the filtered DataFrame:\n", df2)
# Output:
# First row from the filtered DataFrame:
# ('python', 25000, '60days', 2000)
Here,
df.filter(pl.col("Fees") > 23000)creates a new DataFrame with only rows where"Fees"is greater than 23000.filtered_df.row(0)retrieves the first row from the filtered DataFrame. The output is a tuple.
<a id="h-conclusion"></a>
Conclusion
In conclusion, the row() function in Polars is a powerful way to retrieve a single row from a DataFrame, either by index or based on a condition. It provides flexibility with both tuple and dictionary (named=True) outputs.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars DataFrame count() Function
- Polars DataFrame limit() Method
- How to Drop Row in Polars
- Polars DataFrame median() Usage & Examples
- Polars DataFrame std() – Usage & Examples
- Polars DataFrame tail() – Usage & Examples
- Polars DataFrame update() – Usage & Examples
- Polars.DataFrame.mean() – Explained by Examples
- Polars DataFrame partition_by() Usage & Examples
<a id="h-references"></a>
