Built with Tutify.io

    AIStudyLabs

    Polars Series cast() – Usage & Examples

    Polars Series cast() – Usage & Examples

    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 –

    <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.

    <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,

    <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,

    <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,

    <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,

    <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,

    <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,

    <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

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

    Reference