Built with Tutify.io

    AIStudyLabs

    Polars DataFrame width Usage & Examples

    Polars DataFrame width Usage & Examples

    In Polars, the DataFrame.width property returns the total number of columns in the DataFrame. It provides a quick and efficient way to examine the structure of your dataset without needing to load or view the full DataFrame.

    In this article, I will explain the Polars DataFrame width Property by using syntax. Through clear examples, you’ll learn how it returns an integer representing the number of columns in a Polars DataFrame.

    Key Points –

    <a id="h-syntax-of-polars-dataframe-width-property"></a>

    Syntax of Polars DataFrame width Property

    Let’s know the syntax of the width property.

    
    # Syntax of width
    property DataFrame.width: int
    

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

    Return Value

    This function returns an integer (int) representing the number of columns in the Polars DataFrame.

    <a id="h-usage-of-polars-dataframe-width-property"></a>

    Usage of Polars DataFrame width Property

    The width property in Polars is a simple and efficient way to get the number of columns in a DataFrame. It is particularly useful for checking the structure of your data quickly.

    To run some examples of the Polars DataFrame width Property, let’s create a Polars DataFrame.

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

    Yields below output.

    To get the number of columns in a Polars DataFrame, you can use the width property.

    
    # Get number of columns
    print("Number of columns (width):", df.width)
    

    Here,

    <a id="h-using-df-width-after-dropping-a-column"></a>

    Using df.width After Dropping a Column

    When you drop a column from a Polars DataFrame, the width property immediately reflects the reduced column count. This is consistent whether the DataFrame contains data or is empty.

    
    # Drop the 'Discount' column
    df_dropped = df.drop("Discount")
    print("After dropping 'Discount', number of columns:", df_dropped.width)
    
    # Output:
    # After dropping 'Discount', number of columns: 3
    

    Here,

    <a id="h-conditional-logic-based-on-width-property"></a>

    Conditional Logic Based on Width Property

    Applying conditional logic based on the width (i.e., number of columns) of a Polars DataFrame can be useful when handling dynamic data, allowing you to perform different actions depending on how many columns are present.

    
    # Check number of columns and act accordingly
    if df.width > 2:
        print("This DataFrame has more than 2 columns.")
    elif df.width == 2:
        print("This DataFrame has exactly 2 columns.")
    else:
        print("This DataFrame has fewer than 2 columns.")
        
    # Output:
    # This DataFrame has more than 2 columns.
    

    Here,

    <a id="h-using-width-on-an-empty-dataframe"></a>

    Using width on an Empty DataFrame

    Using the width property on an empty Polars DataFrame (with 0 rows) still returns the correct number of defined columns. This makes it helpful for validating the structure of a DataFrame, even when it contains no data.

    
    import polars as pl
    
    # Create an empty DataFrame
    empty_df = pl.DataFrame()
    
    # Get the number of columns
    print("Number of columns in empty DataFrame:", empty_df.width)
    
    # Output:
    # Number of columns in empty DataFrame: 0
    

    Here,

    <a id="h-adding-a-new-column-using-width"></a>

    Adding a new column Using width

    When you add a new column to a Polars DataFrame, the width property automatically updates to reflect the increased column count.

    
    import polars as pl
    
    df = pl.DataFrame({
        'Courses': ["Spark", "PySpark", "Hadoop"],
        'Fee': [22000, 25000, 23000]
        
    })
    
    # Add a new column
    df = df.with_columns(
        pl.Series('Discount',[1000, 2300, 1000]) )
    print("New width:", df.width)  
    
    # Output:
    # New width: 3
    

    Here,

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

    Conclusion

    In conclusion, the DataFrame.width property in Polars is a simple yet powerful tool to quickly determine the number of columns in your dataset. Whether you're validating schema, building dynamic data pipelines, or applying conditional logic, width offers a lightweight and efficient way to understand and work with the structure of your DataFrame.

    Happy Learning!!

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

    Related Articles

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

    References