Built with Tutify.io

    AIStudyLabs

    Polars DataFrame rows() Method with Examples

    Polars DataFrame rows() Method with Examples

    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 –

    <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

    <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

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

    Reference