In Polars, transforming a Series (i.e., a single column in a DataFrame) means modifying its values or structure to better fit your data processing needs. This can include arithmetic operations, type conversions, string formatting, and handling missing data.
Transforming a Series into a Polars DataFrame refers to modifying or performing operations on one or more columns (Series) in the DataFrame. In Polars, Series are essentially individual columns, and you can apply various transformations to them, such as applying functions, aggregating, filtering, or changing data types. In this article, I will explain how to transform a series of a Polars dataframe.
Key Points –
- You can perform basic arithmetic operations like addition, subtraction, multiplication, and division on columns (e.g.,
pl.col("column_name") + 10). - Use
pl.col("column_name")to reference a Series (column) in a Polars DataFrame. - Use
cast()to change the data type of a Series (e.g., from integer to float or string). - Leverage
strmethods to perform string transformations like converting text to uppercase, lowercase, or replacing substrings. - Use
fill_null()to replace missing (null or None) values in a Series with a specified value. - Use string methods like
str.to_uppercase()andstr.strip()to manipulate text data in columns
<a id="h-usage-of-transform-a-series-of-a-polars-dataframe"></a>
Usage of Transform a Series of a Polars DataFrame
Transforming a series involves modifying the values or structure of a column (series) in a Polars DataFrame. This can include mathematical operations, type conversions, string manipulations, or applying custom functions to create new data or alter existing values.
First, let’s create a Polars DataFrame.
import polars as pl
df = pl.DataFrame({"numbers":[2, 5, 10, 15, 20]
})
print("Original DataFrame:\n", df)
Yields below output.
To multiply the "numbers" column by 10 in a Polars DataFrame, use the with_columns() method. This involves a simple arithmetic operation applied to each value in the column. In Polars, you achieve this by using the multiplication operator (*) with pl.col(), which represents a column in the DataFrame.
# Multiply the "numbers" column by 10 and add it as a new column
df2 = df.with_columns([
(pl.col("numbers") * 10).alias("numbers_times_10")
])
print("Transformed DataFrame (numbers multiplied by 10):\n", df2)
Here,
pl.col("numbers"): This refers to the"numbers"column in the DataFrame.(pl.col("numbers") * 10): This multiplies each value in the"numbers"column by 10. So,2 * 10 = 20,5 * 10 = 50, and so on.alias("numbers_times_10"): This gives the new column a name,"numbers_times_10", to store the results.with_columns(): This method adds the newly created column to the existing DataFrame.
<a id="h-take-the-square-of-each-number"></a>
Take the Square of Each Number
To take the square of each number in the "numbers" column of your Polars DataFrame, you can use either arithmetic or apply().
# Square each number
df2 = df.with_columns([
(pl.col("numbers") ** 2).alias("squared")
])
print("Transformed DataFrame (squared values):\n", df2)
# Output:
# Transformed DataFrame (squared values):
# shape: (5, 2)
┌─────────┬─────────┐
│ numbers ┆ squared │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════════╪═════════╡
│ 2 ┆ 4 │
│ 5 ┆ 25 │
│ 10 ┆ 100 │
│ 15 ┆ 225 │
│ 20 ┆ 400 │
└─────────┴─────────┘
Here,
pl.col("numbers") ** 2: Squares each number.alias("squared"): Names the new column"squared".with_columns(...): Adds the new column to the DataFrame.
<a id="h-convert-a-column-to-float"></a>
Convert a Column to Float
To convert the "numbers" column to float in a Polars DataFrame, use the cast() method within with_columns(). This changes the column’s data type to a floating-point number (e.g., 2 becomes 2.0), which is helpful for maintaining precision or preparing the data for operations like division.
# Convert 'numbers' column to float
df2 = df.with_columns([
pl.col("numbers").cast(pl.Float64).alias("numbers_as_float")
])
print("Transformed DataFrame (numbers as float):\n", df2)
# Output:
# Transformed DataFrame (numbers as float):
# shape: (5, 2)
┌─────────┬──────────────────┐
│ numbers ┆ numbers_as_float │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════════╪══════════════════╡
│ 2 ┆ 2.0 │
│ 5 ┆ 5.0 │
│ 10 ┆ 10.0 │
│ 15 ┆ 15.0 │
│ 20 ┆ 20.0 │
└─────────┴──────────────────┘
Here,
pl.col("numbers"): selects the column named"numbers".cast(pl.Float64): changes its type to 64-bit float.with_columns(...): applies the transformation to the DataFrame.
<a id="h-convert-numeric-values-to-strings"></a>
Convert Numeric Values to Strings
To convert the numeric values in the "numbers" column to strings in a Polars DataFrame, use the cast() method with pl.Utf8 for string conversion inside with_columns(). This allows you to change the data type of the column to a string (e.g., numeric values are converted to text).
# Convert 'numbers' column to string
df2 = df.with_columns([
pl.col("numbers").cast(pl.Utf8).alias("numbers_as_string")
])
print("Transformed DataFrame (numbers as string):\n", df2)
# Output:
# Transformed DataFrame (numbers as string):
# shape: (5, 2)
┌─────────┬───────────────────┐
│ numbers ┆ numbers_as_string │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════════╪═══════════════════╡
│ 2 ┆ 2 │
│ 5 ┆ 5 │
│ 10 ┆ 10 │
│ 15 ┆ 15 │
│ 20 ┆ 20 │
└─────────┴───────────────────┘
Here,
pl.col("numbers"): selects the"numbers"column.cast(pl.Utf8): casts the values in the column to strings (i.e.,pl.Utf8is the type for string data in Polars).with_columns(...): applies the transformation and returns a new DataFrame with the converted column.
<a id="h-convert-text-to-uppercase"></a>
Convert Text to Uppercase
To convert text to uppercase in a Polars DataFrame, you use the str.to_uppercase() method, which is specifically designed for transforming string columns. This method changes all the characters in the selected string column to uppercase (capital letters).
import polars as pl
df = pl.DataFrame({"text_column": ["apple", "banana", "cherry"]})
# Convert 'text_column' to uppercase
df2 = df.with_columns([
pl.col("text_column").str.to_uppercase().alias("uppercase_text")
])
print("\nTransformed DataFrame (text to uppercase):\n", df2)
# Output:
# Transformed DataFrame (text to uppercase):
# shape: (3, 2)
┌─────────────┬────────────────┐
│ text_column ┆ uppercase_text │
│ --- ┆ --- │
│ str ┆ str │
╞═════════════╪════════════════╡
│ apple ┆ APPLE │
│ banana ┆ BANANA │
│ cherry ┆ CHERRY │
└─────────────┴────────────────┘
Here,
str.to_uppercase(): Converts all characters in a string column to uppercase.alias("uppercase_text"): Optionally creates a new column to store the transformed values.with_columns(): This function is used to apply the transformation and return the updated DataFrame.
<a id="h-fill-missing-values"></a>
Fill missing values
To fill missing values (i.e., None or null values) in a column of a Polars DataFrame, you can use the fill_null() method. You can specify a value to replace the missing entries, such as 0, "N/A", or any other value that makes sense for your data.
import polars as pl
df = pl.DataFrame({"numbers": [2, None, 10, None, 20]})
# Fill missing values in 'numbers' column with 0
df2 = df.with_columns([
pl.col("numbers").fill_null(0).alias("numbers_filled")
])
print("Transformed DataFrame (missing values filled with 0):\n", df2)
# Output:
# Transformed DataFrame (missing values filled with 0):
# shape: (5, 2)
┌─────────┬────────────────┐
│ numbers ┆ numbers_filled │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════════╪════════════════╡
│ 2 ┆ 2 │
│ null ┆ 0 │
│ 10 ┆ 10 │
│ null ┆ 0 │
│ 20 ┆ 20 │
└─────────┴────────────────┘
<a id="h-conclusion"></a>
Conclusion
In conclusion, transforming a Series into a Polars DataFrame is a powerful way to manipulate and prepare your data. Whether you're performing arithmetic operations, changing data types, formatting strings, or handling missing values, Polars provides efficient and expressive methods like with_columns(), cast(), str.to_uppercase(), and fill_null() to make these transformations straightforward.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- How to Convert Struct to Series in Polars?
- How to Remove Duplicate Columns in Polars?
- Add a New Column into an Existing Polars DataFrame
- Conditional Assignment in Polars DataFrame
- How to Update the Polars DataFrame
- Check if any Value in a Polars DataFrame is True
- Polars Counting Elements in List Column
- Convert Polars Casting a Column to Decimal
- Polars Looping Through the Rows in a Dataset
- Mapping a Python Dict to a Polars Series
- Removing Null Values on Selected Columns only in Polars DataFrame
<a id="h-reference"></a>
