In Polars, making a constant column means adding a new column to a DataFrame where every row has the same fixed value. When you use with_columns() to add this constant column, it returns a new DataFrame that includes the added column. Since Polars is immutable, the original DataFrame remains unchanged. In this article, I will demonstrate how to make a constant column in polars.
Key Points–
- Use
pl.lit()to define a constant value for a new column across all rows. - Chain
with_columns()on the DataFrame to add the constant column. - Always assign a name using
alias("column_name")when adding the column. - Adding a constant column is useful for metadata, tags, or default flags in data pipelines.
- You can create constant columns of any data type: string, integer, float, boolean, datetime, null, or list.
- You can add multiple constant columns at once by passing a list to
with_columns(). pl.lit()ensures the value is broadcast across the entire DataFrame.
<a id="h-usage-of-make-a-constant-column"></a>
Usage of Make a Constant Column
To add a constant column in a Polars DataFrame, use the with_columns() method along with pl.lit() to create a new column where every row has the same value.
To run some examples of how to make a constant column in polars, let’s create a Polars DataFrame.
import polars as pl
technologies= {
'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
'Fees' :[22000,25000,23000,24000,26000],
'Duration':['30days','50days','35days', '40days','55days'],
'Discount':[1000,2300,1000,1200,2500]
}
df = pl.DataFrame(technologies)
print("Original DataFrame:\n", df)
Yields below output.
If you want to add a metadata or tags column in your Polars DataFrame, and if each row should have the same tag (i.e., constant), you can follow the same approach using pl.lit().
# Add a constant metadata/tags column
df2 = df.with_columns(
pl.lit("Data Engineering").alias("Tags"))
print("DataFrame with Tags column:\n", df2)
Yields below output.
<a id="h-add-a-constant-integer-column"></a>
Add a Constant Integer Column
To add a constant integer column in a Polars DataFrame, you can use pl.lit() along with alias("") inside with_columns() function.
# Add a constant integer column
df2 = df.with_columns([
pl.lit(1).alias("constant_column")
])
print("DataFrame with constant integer column:\n", df2)
# Output:
# DataFrame with constant integer column:
# shape: (5, 5)
┌─────────┬───────┬──────────┬──────────┬─────────────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount ┆ constant_column │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 ┆ i32 │
╞═════════╪═══════╪══════════╪══════════╪═════════════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000 ┆ 1 │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300 ┆ 1 │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000 ┆ 1 │
│ Python ┆ 24000 ┆ 40days ┆ 1200 ┆ 1 │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500 ┆ 1 │
└─────────┴───────┴──────────┴──────────┴─────────────────┘
<a id="h-add-a-constant-float-column"></a>
Add a Constant Float Column
To add a constant float column in a Polars DataFrame, you can again use pl.lit() and specify a float value. Polars will automatically infer the type, or you can explicitly cast it to pl.Float64 or pl.Float32.
# Add a constant float column
df2 = df.with_columns([
pl.lit(5.5).alias("Tax")
])
print("DataFrame with constant float column:\n", df2)
# Output:
# DataFrame with constant float column:
# shape: (5, 5)
┌─────────┬───────┬──────────┬──────────┬─────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount ┆ Tax │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 ┆ f64 │
╞═════════╪═══════╪══════════╪══════════╪═════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000 ┆ 5.5 │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300 ┆ 5.5 │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000 ┆ 5.5 │
│ Python ┆ 24000 ┆ 40days ┆ 1200 ┆ 5.5 │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500 ┆ 5.5 │
└─────────┴───────┴──────────┴──────────┴─────┘
<a id="h-add-a-constant-boolean-column"></a>
Add a Constant Boolean Column
To add a constant boolean column in a Polars DataFrame, use pl.lit(True) or pl.lit(False) along with alias(""). This is especially useful for adding flags, status indicators, and other binary values.
# Add a constant boolean column
df2 = df.with_columns([
pl.lit(True).alias("Is_Active")
])
print("DataFrame with constant boolean column:\n", df2)
# Output:
# DataFrame with constant boolean column:
# shape: (5, 5)
┌─────────┬───────┬──────────┬──────────┬───────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount ┆ Is_Active │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 ┆ bool │
╞═════════╪═══════╪══════════╪══════════╪═══════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000 ┆ true │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300 ┆ true │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000 ┆ true │
│ Python ┆ 24000 ┆ 40days ┆ 1200 ┆ true │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500 ┆ true │
└─────────┴───────┴──────────┴──────────┴───────────┘
<a id="h-add-a-constant-null-column"></a>
Add a Constant Null Column
To add a constant null column in a Polars DataFrame, you can use pl.lit(None) and explicitly cast it to a data type, since None alone doesn't carry type information.
# Add a constant null column
df2 = df.with_columns([
pl.lit(None).cast(pl.Utf8).alias("Remarks")
])
print("DataFrame with constant null column:\n", df2)
# Output:
# DataFrame with constant null column:
# shape: (5, 5)
┌─────────┬───────┬──────────┬──────────┬─────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount ┆ Remarks │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 ┆ str │
╞═════════╪═══════╪══════════╪══════════╪═════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000 ┆ null │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300 ┆ null │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000 ┆ null │
│ Python ┆ 24000 ┆ 40days ┆ 1200 ┆ null │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500 ┆ null │
└─────────┴───────┴──────────┴──────────┴─────────┘
<a id="h-add-a-constant-list-column-same-list-for-every-row"></a>
Add a Constant List Column (Same List for Every Row)
To add a constant list column in a Polars DataFrame, i.e., the same list value repeated across all rows, you can use pl.lit() with a list and cast it to a pl.List of the appropriate data type.
# Add constant list column
df2 = df.with_columns([
pl.lit(["Basics", "Advanced"]).cast(pl.List(pl.Utf8)).alias("Topics")
])
print("DataFrame with constant list column:\n", df2)
# Output:
# DataFrame with constant list column:
# shape: (5, 5)
┌─────────┬───────┬──────────┬──────────┬────────────────────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount ┆ Topics │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 ┆ list[str] │
╞═════════╪═══════╪══════════╪══════════╪════════════════════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000 ┆ ["Basics", "Advanced"] │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300 ┆ ["Basics", "Advanced"] │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000 ┆ ["Basics", "Advanced"] │
│ Python ┆ 24000 ┆ 40days ┆ 1200 ┆ ["Basics", "Advanced"] │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500 ┆ ["Basics", "Advanced"] │
└─────────┴───────┴──────────┴──────────┴────────────────────────┘
<a id="h-conclusion"></a>
Conclusion
In conclusion, adding a constant column in Polars is simple and powerful using pl.lit() with alias(). Whether it's a string, number, or boolean, this approach is great for tagging rows, setting default values, or creating flags for downstream logic.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Extract Value of Polars Literal
- Polars Filter by Column Value
- Convert Polars String to Integer
- Polars Rename Columns to Lowercase
- How to Select Last Column of Polars DataFrame
- How to Change Position of a Column in Polars
- Reorder Columns in a Specific Order Using Polars
- How to Convert a Polars DataFrame to Python List?
- Append or Concatenate Two DataFrames in Polars
- How to Add a Column with Numerical Value in Polars
- Get First N Characters from a String Column in Polars
<a id="h-references"></a>
