Built with Tutify.io

    AIStudyLabs

    How to Add a Column with Numerical Value in Polars

    How to Add a Column with Numerical Value in Polars

    In Polars, adding a column with a numerical value to a DataFrame means inserting a new column where each row holds the same constant number or a value derived from existing columns. This can be achieved using the with_columns() method. By leveraging functions like pl.lit(), pl.Series(), and various column operations, you can efficiently enrich your dataset with valuable insights. In this article, I will explain how to add a column with a numerical value in Polars DataFrame.

    Key Points –

    <a id="h-usage-of-add-a-column-with-numerical-value"></a>

    Usage of Add a Column with Numerical Value

    You can add a numerical column to a Polars DataFrame using the with_columns() method. This is a fundamental operation in data processing and analysis, commonly used to assign a constant value across all rows or derive new values from existing columns.

    To run some examples of how to add a column with a numerical value in Polars, let’s create a Polars DataFrame.

    
    import polars as pl
    
    studentdetails = {
           "Studentname":["Ram", "Sam", "Scott", "Ann", "John"],
           "Mathematics" :[80,90,85,72,95],
           "Science" :[85,95,80,90,92],
                  }
    df = pl.DataFrame(studentdetails)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To add a new column with a list of numerical values to your Polars DataFrame, use the with_columns() method. You can also include a column with varying numerical values for each row by providing a list.

    
    # Adding a new column "English" with numerical values
    df2 = df.with_columns(pl.Series("English", [78, 88, 82, 85, 90]))
    print("Updated DataFrame:\n", df2) 
    
    # Output:
    # Updated DataFrame:
    # shape: (5, 4)
    ┌─────────────┬─────────────┬─────────┬─────────┐
    │ Studentname ┆ Mathematics ┆ Science ┆ English │
    │ ---         ┆ ---         ┆ ---     ┆ ---     │
    │ str         ┆ i64         ┆ i64     ┆ i64     │
    ╞═════════════╪═════════════╪═════════╪═════════╡
    │ Ram         ┆ 80          ┆ 85      ┆ 78      │
    │ Sam         ┆ 90          ┆ 95      ┆ 88      │
    │ Scott       ┆ 85          ┆ 80      ┆ 82      │
    │ Ann         ┆ 72          ┆ 90      ┆ 85      │
    │ John        ┆ 95          ┆ 92      ┆ 90      │
    └─────────────┴─────────────┴─────────┴─────────┘
    

    Here,

    <a id="h-adding-a-column-with-a-constant-numerical-value"></a>

    Adding a Column with a Constant Numerical Value

    If you want to add a column where each row has the same numerical value, you can use the with_columns() method to insert a constant numerical value into your Polars DataFrame.

    
    # Adding a new column "TotalMarks" with a constant value 100
    df2 = df.with_columns(pl.lit(100).alias("TotalMarks"))
    print("Updated DataFrame:\n", df2)
    
    # Output:
    # Updated DataFrame:
    # shape: (5, 4)
    ┌─────────────┬─────────────┬─────────┬────────────┐
    │ Studentname ┆ Mathematics ┆ Science ┆ TotalMarks │
    │ ---         ┆ ---         ┆ ---     ┆ ---        │
    │ str         ┆ i64         ┆ i64     ┆ i32        │
    ╞═════════════╪═════════════╪═════════╪════════════╡
    │ Ram         ┆ 80          ┆ 85      ┆ 100        │
    │ Sam         ┆ 90          ┆ 95      ┆ 100        │
    │ Scott       ┆ 85          ┆ 80      ┆ 100        │
    │ Ann         ┆ 72          ┆ 90      ┆ 100        │
    │ John        ┆ 95          ┆ 92      ┆ 100        │
    └─────────────┴─────────────┴─────────┴────────────┘
    

    Here,

    <a id="h-adding-a-column-based-on-an-existing-column"></a>

    Adding a Column Based on an Existing Column

    You can also create a new column by applying calculations to existing columns. To add a column based on an existing one in a Polars DataFrame, use the with_columns() method and perform operations on the existing data.

    
    # Adding a new column "Percentage" based on Mathematics and Science
    df2 = df.with_columns(((df["Mathematics"] + df["Science"]) / 2).alias("Percentage"))
    print("Updated DataFrame:\n", df2)
    
    # Output:
    # Updated DataFrame:
    # shape: (5, 4)
    ┌─────────────┬─────────────┬─────────┬────────────┐
    │ Studentname ┆ Mathematics ┆ Science ┆ Percentage │
    │ ---         ┆ ---         ┆ ---     ┆ ---        │
    │ str         ┆ i64         ┆ i64     ┆ f64        │
    ╞═════════════╪═════════════╪═════════╪════════════╡
    │ Ram         ┆ 80          ┆ 85      ┆ 82.5       │
    │ Sam         ┆ 90          ┆ 95      ┆ 92.5       │
    │ Scott       ┆ 85          ┆ 80      ┆ 82.5       │
    │ Ann         ┆ 72          ┆ 90      ┆ 81.0       │
    │ John        ┆ 95          ┆ 92      ┆ 93.5       │
    └─────────────┴─────────────┴─────────┴────────────┘
    

    Here,

    <a id="h-adding-multiple-columns"></a>

    Adding Multiple Columns

    To add multiple columns at once, you can use the with_columns() method. This approach is efficient and enables you to create new columns using existing data or constant values.

    
    # adding multiple columns at once
    df2 = df.with_columns([
        pl.lit(35).alias("Passing Marks"),
        (df["Mathematics"] >= 85).alias("Passed_Math")
    ])
    print("Updated DataFrame:\n", df2) 
    
    # Output:
    # Updated DataFrame:
    # shape: (5, 5)
    ┌─────────────┬─────────────┬─────────┬───────────────┬─────────────┐
    │ Studentname ┆ Mathematics ┆ Science ┆ Passing Marks ┆ Passed_Math │
    │ ---         ┆ ---         ┆ ---     ┆ ---           ┆ ---         │
    │ str         ┆ i64         ┆ i64     ┆ i32           ┆ bool        │
    ╞═════════════╪═════════════╪═════════╪═══════════════╪═════════════╡
    │ Ram         ┆ 80          ┆ 85      ┆ 35            ┆ false       │
    │ Sam         ┆ 90          ┆ 95      ┆ 35            ┆ true        │
    │ Scott       ┆ 85          ┆ 80      ┆ 35            ┆ true        │
    │ Ann         ┆ 72          ┆ 90      ┆ 35            ┆ false       │
    │ John        ┆ 95          ┆ 92      ┆ 35            ┆ true        │
    └─────────────┴─────────────┴─────────┴───────────────┴─────────────┘
    

    <a id="h-add-a-column-by-summing-two-columns"></a>

    Add a Column by Summing Two Columns

    You can create a new column by summing two existing columns using the with_columns() function. Let’s calculate the total marks for Mathematics + Science and store it in a new column "Total Marks".

    
    # Adding a new column by summing Mathematics and Science
    df2 = df.with_columns((df["Mathematics"] + df["Science"]).alias("Total Marks"))
    print("Updated DataFrame:\n", df2) 
    
    # Output:
    # Updated DataFrame:
    # shape: (5, 4)
    ┌─────────────┬─────────────┬─────────┬─────────────┐
    │ Studentname ┆ Mathematics ┆ Science ┆ Total Marks │
    │ ---         ┆ ---         ┆ ---     ┆ ---         │
    │ str         ┆ i64         ┆ i64     ┆ i64         │
    ╞═════════════╪═════════════╪═════════╪═════════════╡
    │ Ram         ┆ 80          ┆ 85      ┆ 165         │
    │ Sam         ┆ 90          ┆ 95      ┆ 185         │
    │ Scott       ┆ 85          ┆ 80      ┆ 165         │
    │ Ann         ┆ 72          ┆ 90      ┆ 162         │
    │ John        ┆ 95          ┆ 92      ┆ 187         │
    └─────────────┴─────────────┴─────────┴─────────────┘
    

    Here,

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

    Conclusion

    In conclusion, adding a numerical column in Polars is straightforward and highly flexible using the with_columns() method. Whether you're adding a constant value, a list of values, or performing calculations based on existing columns, Polars provides an efficient and expressive way to manipulate DataFrames. By utilizing functions like pl.lit(), pl.Series(), and column operations, you can enhance your dataset with new insights seamlessly.

    Happy Learning!!

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

    Related Articles

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

    References