Built with Tutify.io

    AIStudyLabs

    Polars DataFrame head() Function

    Polars DataFrame head() Function

    In Polars, the head() function is used to retrieve the first few rows of a DataFrame. By default, it returns the first five rows, but you can customize the number by specifying an integer as an argument. Similar to Pandas' head() function, it is useful for quickly examining the structure of a DataFrame.

    In this article, I will explain the Polars DataFrame head() function by using its syntax, parameters, usage, and how to return a new DataFrame containing the first n rows of the original DataFrame.

    Key Points –

    <a id="h-polars-dataframe-head-introduction"></a>

    Polars DataFrame head() Introduction

    Let’s know the syntax of the head() method.

    
    # Syntax of head()
    DataFrame.head(n: int = 5) → DataFrame
    

    <a id="h-parameters-of-the-nbsp-dataframe-head"></a>

    Parameters of the DataFrame head()

    It allows only one parameter.

    <a id="h-return-value"></a>

    Return Value

    This function returns a new DataFrame containing the first n rows.

    <a id="h-usage-of-polars-dataframe-head-function"></a>

    Usage of Polars DataFrame head() Function

    The head() function returns the first n rows of a Polars DataFrame, allowing users to preview the top rows of their dataset.

    To run some examples of the Polars DataFrame head() function, let’s create a Polars DataFrame.

    
    import polars as pl
    
    technologies= {
        'Courses':["Spark", "PySpark", "Hadoop", "Python", "Pandas", "PySpark", "Java"],
        'Fee' :[22000, 25000, 23000, 24000, 26000, 30000, 35000],
        'Discount':[1000, 2300, 1000, 1200, 2500, 2000, 2200],
        'Duration':['35days', '40days', '45days', '60days', '30days', '50days', '65days']
              }
    
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n",df)
    

    Yields below output.

    By default, the head() function in Polars returns the first 5 rows of a DataFrame when no argument is specified.

    
    # Using head() to return the first 5 rows
    print("First 5 rows of the DataFrame (default usage):\n", df.head())
    

    Here,

    <a id="h-specifying-the-number-of-rows-n-3"></a>

    Specifying the Number of Rows (n=3)

    Alternatively, you can specify the number of rows to return using the n parameter in the head() function by passing an integer argument. This allows you to preview a custom number of rows from the start of a DataFrame.

    
    # Get the first 3 rows
    print("First 3 rows of the DataFrame:\n", df.head(3))
    
    # Output:
    # First 3 rows of the DataFrame:
    # shape: (3, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fee   ┆ Discount ┆ Duration │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ i64      ┆ str      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 1000     ┆ 35days   │
    │ PySpark ┆ 25000 ┆ 2300     ┆ 40days   │
    │ Hadoop  ┆ 23000 ┆ 1000     ┆ 45days   │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-using-head-on-a-multi-column-dataframe"></a>

    Using head() on a Multi-Column DataFrame

    The head() function works effortlessly with multi-column DataFrames, enabling you to preview the first few rows across various columns, regardless of data types such as strings, integers, or floats.

    
    # Get the first 4 rows
    result = df.head(4)
    print("Getting the first 4 rows:\n", result)
    
    # Output:
    # Getting the first 4 rows:
    # shape: (4, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fee   ┆ Discount ┆ Duration │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ i64      ┆ str      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 1000     ┆ 35days   │
    │ PySpark ┆ 25000 ┆ 2300     ┆ 40days   │
    │ Hadoop  ┆ 23000 ┆ 1000     ┆ 45days   │
    │ Python  ┆ 24000 ┆ 1200     ┆ 60days   │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-combining-head-with-select"></a>

    Combining head() with select()

    You can use the select() method to choose specific columns and then apply the head() function to retrieve only the first n rows. This is useful when dealing with large DataFrames but only needing a subset of data.

    
    # Select specific columns and get the first 3 rows
    result = df.select(["Courses", "Fee", "Discount"]).head(3)
    print("Select specific columns:\n",result)
    
    # Output:
    # Select specific columns:
    # shape: (3, 3)
    ┌─────────┬───────┬──────────┐
    │ Courses ┆ Fee   ┆ Discount │
    │ ---     ┆ ---   ┆ ---      │
    │ str     ┆ i64   ┆ i64      │
    ╞═════════╪═══════╪══════════╡
    │ Spark   ┆ 22000 ┆ 1000     │
    │ PySpark ┆ 25000 ┆ 2300     │
    │ Hadoop  ┆ 23000 ┆ 1000     │
    └─────────┴───────┴──────────┘
    

    Here,

    <a id="h-using-head-with-filtering"></a>

    Using head() with Filtering

    Similarly, you can combine head() with filtering operations to preview a subset of rows that meet specific conditions. This is useful for quickly inspecting relevant data after applying filters.

    
    # Filtering courses with a fee greater than 24000 and applying head()
    result = df.filter(pl.col("Fee") > 24000).head(3)
    print(result)
    
    # Output:
    # shape: (3, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fee   ┆ Discount ┆ Duration │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ i64      ┆ str      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ PySpark ┆ 25000 ┆ 2300     ┆ 40days   │
    │ Pandas  ┆ 26000 ┆ 2500     ┆ 30days   │
    │ PySpark ┆ 30000 ┆ 2000     ┆ 50days   │
    └─────────┴───────┴──────────┴──────────┘
    

    <a id="h-using-head-with-a-negative-value"></a>

    Using head() with a Negative Value

    Finally, you can use a negative value with head(n) to exclude the last n rows from the DataFrame. This is helpful when you need to remove a certain number of rows from the end while retaining the rest.

    
    # # Using head() with a negative value 
    # To exclude the last 3 rows
    result = df.head(-3)
    print(result)
    
    # Output:
    # shape: (4, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ Courses ┆ Fee   ┆ Discount ┆ Duration │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ i64      ┆ str      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 1000     ┆ 35days   │
    │ PySpark ┆ 25000 ┆ 2300     ┆ 40days   │
    │ Hadoop  ┆ 23000 ┆ 1000     ┆ 45days   │
    │ Python  ┆ 24000 ┆ 1200     ┆ 60days   │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

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

    Conclusion

    In this article, I have explained the Polars DataFrame head() function, covering its syntax, parameters, usage, and how it returns a new DataFrame with the first n rows, along with examples.

    Happy Learning!!

    <a id="h-related-articles"></a>

    Related Articles

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

    Reference