Built with Tutify.io

    AIStudyLabs

    Convert Polars Cast Float to String

    Convert Polars Cast Float to String

    In Polars, you can convert a float column to a string type by using the cast() method with pl.Utf8. This function allows you to change a column's data type, and to convert a float column to a string, you specify the Utf8 type, which represents strings in Polars. In this article, I will explain how to convert polars cast float to string.

    Key Points –

    <a id="h-usage-of-polars-float-to-string"></a>

    Usage of Polars Float to String

    Converting a float column to a string in Polars is simple with the cast() method. This method facilitates type conversion, allowing you to change a column's data type to any desired type, including strings. To convert a float column to a string, apply .cast(pl.Utf8) on the target column.

    To run some examples of converting polars cast float to string, let’s create a Polars DataFrame.

    
    import polars as pl
    
    technologies= {
        'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
        'Fees' :[22000.30,25000.40,23000.20,24000.50,26000.10],
        'Duration':['30days','50days','35days', '40days','55days'],
        'Discount':[1000.10,2300.15,1000.5,1200.22,2500.20]
              }
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To perform a basic conversion of float values to string in the Fee and Discount columns of the DataFrame, you can use the cast() function to convert those columns from float to string.

    
    # Casting 'Fees' and 'Discount' from float to string
    df2 = df.with_columns([
        pl.col("Fees").cast(pl.Utf8).alias("Fees"),
        pl.col("Discount").cast(pl.Utf8).alias("Discount")
    ])
    print("DataFrame after conversion:\n", df2)
    

    In the above example, both the Fees and Discount columns are cast to string types using the with_columns() method in one step.

    <a id="h-cast-single-column-from-float-to-string"></a>

    Cast Single Column from Float to String

    To cast a single column from float to string in Polars, you can use the cast() function specifically on that column and then update the DataFrame using the with_columns() method.

    
    # Using Casting a Single Column from Float to String
    df_casted = df.with_columns(
        df['Fees'].cast(pl.Utf8).alias('Fees'))
    print("DataFrame with 'Fees' casted to String:\n", df_casted)
    
    # Output:
    # DataFrame with 'Fees' casted to String:
    # shape: (5, 4)
    ┌─────────┬─────────┬──────────┬──────────┐
    │ Courses ┆ Fees    ┆ Duration ┆ Discount │
    │ ---     ┆ ---     ┆ ---      ┆ ---      │
    │ str     ┆ str     ┆ str      ┆ f64      │
    ╞═════════╪═════════╪══════════╪══════════╡
    │ Spark   ┆ 22000.3 ┆ 30days   ┆ 1000.1   │
    │ PySpark ┆ 25000.4 ┆ 50days   ┆ 2300.15  │
    │ Hadoop  ┆ 23000.2 ┆ 35days   ┆ 1000.5   │
    │ Python  ┆ 24000.5 ┆ 40days   ┆ 1200.22  │
    │ Pandas  ┆ 26000.1 ┆ 55days   ┆ 2500.2   │
    └─────────┴─────────┴──────────┴──────────┘
    

    Here,

    <a id="h-cast-multiple-columns-from-float-to-string"></a>

    Cast Multiple Columns from Float to String

    To cast multiple columns from float to string in Polars, you can utilize the with_columns() method along with the cast() method for each column you want to convert. Here's how you can cast both the Fees and Discount columns from float to string.

    
    # Casting multiple columns from float to string
    df_casted = df.with_columns([
            df['Fees'].cast(pl.Utf8).alias('Fees'),
            df['Discount'].cast(pl.Utf8).alias('Discount')])
    print("DataFrame with 'Fees' and 'Discount' casted to String:\n", df_casted)
    
    # Output:
    # DataFrame with 'Fees' and 'Discount' casted to String:
     shape: (5, 4)
    ┌─────────┬─────────┬──────────┬──────────┐
    │ Courses ┆ Fees    ┆ Duration ┆ Discount │
    │ ---     ┆ ---     ┆ ---      ┆ ---      │
    │ str     ┆ str     ┆ str      ┆ str      │
    ╞═════════╪═════════╪══════════╪══════════╡
    │ Spark   ┆ 22000.3 ┆ 30days   ┆ 1000.1   │
    │ PySpark ┆ 25000.4 ┆ 50days   ┆ 2300.15  │
    │ Hadoop  ┆ 23000.2 ┆ 35days   ┆ 1000.5   │
    │ Python  ┆ 24000.5 ┆ 40days   ┆ 1200.22  │
    │ Pandas  ┆ 26000.1 ┆ 55days   ┆ 2500.2   │
    └─────────┴─────────┴──────────┴──────────┘
    

    Here,

    <a id="h-cast-float-to-string-after-mathematical-operation"></a>

    Cast Float to String After Mathematical Operation

    To cast a float to a string after performing a mathematical operation in Polars, you can first apply the operation on the column and then use cast() to convert the result into a string.

    
    # Cast float to string after mathematical operation
    df_casted = df.with_columns(
        (df['Fees'] * 1.1).cast(pl.Utf8).alias('Fees'))
    print("DataFrame with 'Fees' after multiplication and casted to String:\n", df_casted)
    
    # Output:
    # DataFrame with 'Fees' after multiplication and casted to String:
    # shape: (5, 4)
    ┌─────────┬────────────────────┬──────────┬──────────┐
    │ Courses ┆ Fees               ┆ Duration ┆ Discount │
    │ ---     ┆ ---                ┆ ---      ┆ ---      │
    │ str     ┆ str                ┆ str      ┆ f64      │
    ╞═════════╪════════════════════╪══════════╪══════════╡
    │ Spark   ┆ 24200.33           ┆ 30days   ┆ 1000.1   │
    │ PySpark ┆ 27500.440000000002 ┆ 50days   ┆ 2300.15  │
    │ Hadoop  ┆ 25300.22           ┆ 35days   ┆ 1000.5   │
    │ Python  ┆ 26400.550000000003 ┆ 40days   ┆ 1200.22  │
    │ Pandas  ┆ 28600.11           ┆ 55days   ┆ 2500.2   │
    └─────────┴────────────────────┴──────────┴──────────┘
    

    Here,

    <a id="h-cast-float-column-to-string-with-precision-handling"></a>

    Cast Float Column to String with Precision Handling

    To cast a float column to a string with precision handling in Polars, you can round the float values to a specific number of decimal places before converting them to strings.

    
    # Cast float column to string with precision handling
    df_casted = df.with_columns(
        (df['Fees'].round(2)).cast(pl.Utf8).alias('Fees'))
    print("DataFrame with 'Fees' rounded to 2 decimal places and casted to String:\n", df_casted)
    
    # Output:
    # DataFrame with 'Fees' rounded to 2 decimal places and casted to String:
    #  shape: (5, 4)
    ┌─────────┬─────────┬──────────┬──────────┐
    │ Courses ┆ Fees    ┆ Duration ┆ Discount │
    │ ---     ┆ ---     ┆ ---      ┆ ---      │
    │ str     ┆ str     ┆ str      ┆ f64      │
    ╞═════════╪═════════╪══════════╪══════════╡
    │ Spark   ┆ 22000.3 ┆ 30days   ┆ 1000.1   │
    │ PySpark ┆ 25000.4 ┆ 50days   ┆ 2300.15  │
    │ Hadoop  ┆ 23000.2 ┆ 35days   ┆ 1000.5   │
    │ Python  ┆ 24000.5 ┆ 40days   ┆ 1200.22  │
    │ Pandas  ┆ 26000.1 ┆ 55days   ┆ 2500.2   │
    └─────────┴─────────┴──────────┴──────────┘
    

    Here,

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

    Conclusion

    In conclusion, converting a float column to a string in Polars is straightforward using the cast() method with pl.Utf8. This process allows you to change the column's data type, making the float values into string representations. By using the with_columns() method, you can create a new column or update an existing one with the converted values.

    Happy Learning!!

    <a id="h-related-articles"></a>

    Related Articles

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

    References