The Polars Series.cast() method is used to change the data type of a Series to another type, like from integers to strings, floats to integers, booleans to integers, and so on. This is particularly useful when the data isn't in the right format for your analysis, or when you want to optimize performance or ensure compatibility with other operations.
In this article, I will explain the cast() method in the Polars Series by using its syntax, parameters, and usage, and demonstrating how it returns a new Series with the specified data type.
Key Points –
- The
cast()method allows for conversion between different data types in a Polars Series, such as integers, floats, booleans, strings, etc. - When converting data that cannot be interpreted correctly (e.g., converting a string "abc" to an integer), the
strict=Falseparameter prevents errors by converting invalid values tonull. - Casting a boolean Series to integers converts
Trueto1andFalseto0. - You can cast to a variety of types, including
Utf8(string),Int8,Int16,Int32,Int64,Float32,Float64,Boolean, and more. - The
cast()method helps optimize memory by casting numerical types to smaller or more efficient types when possible, such as castingInt64toInt32. - When casting numerical types to strings (
Utf8), thecast()method can be useful for preparing data for display or concatenation with other string data. - The
cast()method allows you to convert a Series from one data type to another, such as from integers to strings or floats to integers. - Supports conversion from string representations of numbers to their respective numeric types, such as casting
"10"(string) to10(integer).
<a id="h-polars-series-cast-introduction"></a>
Polars Series cast() Introduction
Let’s know the syntax of the series cast() method.
# Syntax of series cast()
Series.cast(
dtype: type[int | float | str | bool] | PolarsDataType,
*,
strict: bool = True,
wrap_numerical: bool = False,
) → Self
<a id="h-parameters-of-the-polars-series-cast"></a>
Parameters of the Polars Series cast()
Following are the parameters of series cast() method.
dtype(type[int | float | str | bool] | PolarsDataType) -- The target data type to cast the Series to.
- This can be a standard Python type (e.g.,
int,float,str,bool) or a Polars-specific data type (e.g.,pl.Int64,pl.Float32,pl.Utf8).
strict(bool, defaultTrue) -- If
True, the cast operation will raise an error if any value cannot be converted. - If
False, it will insertnullfor values that cannot be converted.
- If
wrap_numerical(bool, defaultFalse) -- If
True, it wraps numerical types (likeintandfloat) into the corresponding Polars data types (pl.Int64,pl.Float64). - If
False, it uses the native Python types.
- If
<a id="h-return-value"></a>
Return Value
This function returns a new Polars Series with the specified data type.
<a id="h-usage-of-polars-series-cast-method"></a>
Usage of Polars Series cast() Method
The cast() method is used to convert a Polars Series from one data type to another. This is particularly useful for ensuring consistency, optimizing calculations, or preparing data for specific operations that require a certain data type (e.g., converting integers to floats or strings to booleans).
Now, let’s create a Polars Series.
import polars as pl
# Sample Series
ser = pl.Series("integers", [10, 20, 30, 40, 50])
print("Original Series:\n", ser)
Yields below output.
To convert integers in a Series to floats, you can use the cast() method to change the Series' data type to Float64. This method in Polars is specifically designed to modify the data type of a column or Series.
# Cast integers to floats
ser_casted = ser.cast(pl.Float64)
print("Series after converting to Floats:\n", ser_casted)
Here,
- The original Series contains integer values.
- Using the cast(
pl.Float64) method, you convert the integer values to floating-point numbers (f64type in Polars). - The decimal point
.0is added to each value because it is now a float.
<a id="h-using-series-cast-to-converting-strings-to-integers"></a>
Using Series cast() to Converting Strings to Integers
To convert strings to integers in Polars, you can use the cast() method, similar to how you would convert integers to floats. The Series.cast() method allows you to transform a Series containing numeric strings into an integer type.
import polars as pl
# Sample Series with string numbers
ser = pl.Series("numbers_as_strings", ["10", "20", "30", "40", "50"])
# Convert strings to integers
ser_int = ser.cast(pl.Int64)
print("Converted Series (to Int):\n", ser_int)
# Output:
# Converted Series (to Int):
# shape: (5,)
# Series: 'numbers_as_strings' [i64]
# [
# 10
# 20
# 30
# 40
# 50
# ]
Here,
- The original series contains string representations of numbers (
strtype). cast(pl.Int64)converts each string to an integer (i64type).- If any value in the Series is not convertible (e.g.
"abc"), Polars will raise an error unless you handle it usingstrict=Falseinsidecast()(available in DataFrames, not Series directly).
<a id="h-using-series-cast-to-convert-floats-to-integers"></a>
Using Series cast() to Convert Floats to Integers
To convert floats to integers in Polars using the Series.cast() method, you can cast the Series to an integer type such as pl.Int64. This will remove the decimal part of the floats through truncation.
import polars as pl
# Sample Series with floats
ser = pl.Series("floats", [10.5, 20.3, 30.7, 40.1, 50.9])
# Cast floats to integers
ser_casted = ser.cast(pl.Int64)
print("Series after converting to Integers:\n", ser_casted)
# Output:
# Series after converting to Integers:
# shape: (5,)
# Series: 'floats' [i64]
# [
# 10
# 20
# 30
# 40
# 50
# ]
Here,
- The original Series contains float values.
- Using the
cast(pl.Int64)method, Polars converts the float values to integers. This operation truncates the decimal part (e.g.,10.5becomes10). - Important: No rounding occurs; the decimal part is simply discarded.
<a id="h-casting-booleans-to-integers-using-series-cast"></a>
Casting Booleans to Integers using Series.cast()
You can convert a pl.Series of boolean values (True/False) to integers (1/0) using cast(pl.Int64) function.
import polars as pl
# Sample Series with boolean values
ser = pl.Series("bools", [True, False, True, True, False])
# Cast to integers
ser_int = ser.cast(pl.Int64)
print("Converted to Integers:\n", ser_int)
# Output:
# Converted to Integers:
# shape: (5,)
# Series: 'bools' [i64]
# [
# 1
# 0
# 1
# 1
# 0
# ]
Here,
Truebecomes1,Falsebecomes0.- You can also use
pl.Int8,pl.Int32, etc., depending on your memory and use case needs. - This is often used for encoding binary features for machine learning or numerical operations.
<a id="h-using-series-cast-to-casting-integers-to-strings"></a>
Using Series cast() to Casting Integers to Strings
You can cast integers to strings in Polars using the Series.cast() method. This enables you to convert a Series of integer values into string values, which is useful for tasks like concatenation or working with categorical data.
import polars as pl
# Sample Series with integers
ser = pl.Series("integers", [10, 20, 30, 40, 50])
# Cast integers to strings
ser_casted = ser.cast(pl.Utf8)
print("Series after converting to Strings:\n", ser_casted)
# Output:
# Series after converting to Strings:
# shape: (5,)
# Series: 'integers' [str]
# [
# "10"
# "20"
# "30"
# "40"
# "50"
# ]
Here,
- The original Series contains integer values.
- After using the
cast(pl.Utf8)method, the Series is converted to strings (Utf8is the Polars type for strings). - This operation is helpful when you want to perform string-specific operations (like concatenation) or convert integers into categories.
<a id="h-handling-invalid-casting-with-strict-false"></a>
Handling Invalid Casting with strict=False
The strict=False parameter in Polars' Series.cast() method is especially helpful when you want to prevent errors during type conversion, particularly in cases where some values may not be convertible.
import polars as pl
# Series with mixed valid and invalid numeric strings
ser = pl.Series("mixed", ["10", "20", "abc", "30", "xyz"])
# Try casting to integers with strict=False
ser_casted = ser.cast(pl.Int64, strict=False)
print("Series after casting with strict=False:\n", ser_casted)
# Output:
# Series after casting with strict=False:
# shape: (5,)
# Series: 'mixed' [i64]
# [
# 10
# 20
# null
# 30
# null
# ]
Here,
"10","20", and"30"were valid integer strings and were successfully casted."abc"and"xyz"were invalid; instead of throwing an error, they became null because strict=False was used.- If you had used
strict=True(default), this would raise an error and stop execution.
<a id="h-conclusion"></a>
Conclusion
In conclusion, the Series.cast() method in Polars is a powerful and flexible tool for converting data types within a Series. Whether you're changing integers to floats, converting strings to integers, or performing other type conversions, this method ensures your data is correctly formatted for analysis and computation. The use of parameters like strict=False helps manage potential conversion errors, making it a reliable option for a wide range of data processing tasks.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars Series head() Method with Examples
- Polars Series tail() Usage & Examples
- Polars Series min() – Explained by Examples
- Polars Series max() Function
- Convert Polars Series to List
- Polars Series filter() Method with Examples
- How to Convert Polars Series to Pandas Series in Python?
<a id="h-reference"></a>
