Built with Tutify.io

    AIStudyLabs

    Polars DataFrame row() Usage & Examples

    Polars DataFrame row() Usage & Examples

    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 –

    <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.

    <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,

    <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,

    <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,

    <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,

    <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,

    <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

    <a id="h-references"></a>

    References