Open In App

Create Column with Fixed Value from Variable Using Python Polars

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Polars is a powerful DataFrame library written in Rust and Python, it's focused on performance, and designed to handle large data efficiently. Adding a column with a fixed value in a Polars DataFrame is easy, let's see how to do this.

Prerequisites

Before you begin, ensure you have Polars installed. You can install it using pip:

pip install polars

Loading Data into Polars DataFrame

I have a data.csv file and let's load some data into a Polars DataFrame from a CSV file. First, we need to import Polars and load data into a data frame.

Python
import polars

df = polars.read_csv('data.csv')
print(df)

Output:

PolarsFixedValueLoadData
Load Data

Adding a Column with Fixed Value

Syntax:

df.with_columns(polars.lit("value").alias('new_column'))

Examples

Example 1. Adding a Column with a Fixed String Value

Python
import polars

df = polars.read_csv('data.csv')

# Add a new column 'country' with a fixed value of "india"
df1 = df.with_columns(polars.lit("india").alias('country'))
print(df1)

Output:

PolarsFixedValueExample1
Adding Column with String value

Example 2. Adding a Column with a Fixed Integer Value

Python
import polars

df = polars.read_csv('data.csv')

# Add a new column 'status' with a fixed value of 1(active)
df2 = df.with_columns(polars.lit(1).alias('status'))
print(df2)

Output:

PolarsFixedValueExample2
Adding Column with Integrer value

Example 3: Adding Multiple Columns with Fixed Values

Python
import polars

df = polars.read_csv('data.csv')

# Add multiple columns with fixed values
df3 = df.with_columns([
    polars.lit('delhi').alias('capital'),
    polars.lit(1.5).alias('rate')
])
print(df3)

Output:

PolarsFixedValueExample3
Adding Multiple Columns

Conclusion

It is possible to add a column in Polars DataFrame with a defined value by using the with_columns and polars.lit() method. This is a helpful technique especially when it comes to creating dataframes or adding default values to what already exists.


Next Article
Article Tags :
Practice Tags :

Similar Reads