The easiest way to accomplish this is with the cast expression.

String to Int/Float

To cast from a string to an integer (or float):

import polars as pl

df = pl.DataFrame({"bar": ["100", "250", "125", ""]})
df.with_columns(pl.col('bar').cast(pl.Int64, strict=False).alias('bar_int'))
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar ┆ bar_int β”‚
β”‚ --- ┆ ---     β”‚
β”‚ str ┆ i64     β”‚
β•žβ•β•β•β•β•β•ͺ═════════║
β”‚ 100 ┆ 100     β”‚
β”‚ 250 ┆ 250     β”‚
β”‚ 125 ┆ 125     β”‚
β”‚     ┆ null    β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

A handy list of available datatypes is here. These are all aliased under polars, so you can refer to them easily (e.g., pl.UInt64).

For the data you describe, I recommend using strict=False to avoid having one mangled number among millions of records result in an exception that halts everything.

Int/Float to String

The same process can be used to convert numbers to strings - in this case, the utf8 datatype.

Let me modify your dataset slightly:

df = pl.DataFrame({"bar": [100.5, 250.25, 1250000, None]})
df.with_columns(pl.col("bar").cast(pl.String, strict=False).alias("bar_string"))
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar    ┆ bar_string β”‚
β”‚ ---    ┆ ---        β”‚
β”‚ f64    ┆ str        β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ════════════║
β”‚ 100.5  ┆ 100.5      β”‚
β”‚ 250.25 ┆ 250.25     β”‚
β”‚ 1.25e6 ┆ 1250000.0  β”‚
β”‚ null   ┆ null       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

If you need more control over the formatting, you can use the map_elements method and Python's new f-string formatting.

df.with_columns(
    pl.col("bar").map_elements(lambda x: f"This is ${x:,.2f}!").alias("bar_fstring")
)
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar    ┆ bar_fstring            β”‚
β”‚ ---    ┆ ---                    β”‚
β”‚ f64    ┆ str                    β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ════════════════════════║
β”‚ 100.5  ┆ This is $100.50!       β”‚
β”‚ 250.25 ┆ This is $250.25!       β”‚
β”‚ 1.25e6 ┆ This is $1,250,000.00! β”‚
β”‚ null   ┆ null                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

I found this web page to be a handy reference for those unfamiliar with f-string formatting.

Answer from user18559875 on Stack Overflow
Top answer
1 of 3
22

The easiest way to accomplish this is with the cast expression.

String to Int/Float

To cast from a string to an integer (or float):

import polars as pl

df = pl.DataFrame({"bar": ["100", "250", "125", ""]})
df.with_columns(pl.col('bar').cast(pl.Int64, strict=False).alias('bar_int'))
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar ┆ bar_int β”‚
β”‚ --- ┆ ---     β”‚
β”‚ str ┆ i64     β”‚
β•žβ•β•β•β•β•β•ͺ═════════║
β”‚ 100 ┆ 100     β”‚
β”‚ 250 ┆ 250     β”‚
β”‚ 125 ┆ 125     β”‚
β”‚     ┆ null    β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

A handy list of available datatypes is here. These are all aliased under polars, so you can refer to them easily (e.g., pl.UInt64).

For the data you describe, I recommend using strict=False to avoid having one mangled number among millions of records result in an exception that halts everything.

Int/Float to String

The same process can be used to convert numbers to strings - in this case, the utf8 datatype.

Let me modify your dataset slightly:

df = pl.DataFrame({"bar": [100.5, 250.25, 1250000, None]})
df.with_columns(pl.col("bar").cast(pl.String, strict=False).alias("bar_string"))
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar    ┆ bar_string β”‚
β”‚ ---    ┆ ---        β”‚
β”‚ f64    ┆ str        β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ════════════║
β”‚ 100.5  ┆ 100.5      β”‚
β”‚ 250.25 ┆ 250.25     β”‚
β”‚ 1.25e6 ┆ 1250000.0  β”‚
β”‚ null   ┆ null       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

If you need more control over the formatting, you can use the map_elements method and Python's new f-string formatting.

df.with_columns(
    pl.col("bar").map_elements(lambda x: f"This is ${x:,.2f}!").alias("bar_fstring")
)
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar    ┆ bar_fstring            β”‚
β”‚ ---    ┆ ---                    β”‚
β”‚ f64    ┆ str                    β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ════════════════════════║
β”‚ 100.5  ┆ This is $100.50!       β”‚
β”‚ 250.25 ┆ This is $250.25!       β”‚
β”‚ 1.25e6 ┆ This is $1,250,000.00! β”‚
β”‚ null   ┆ null                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

I found this web page to be a handy reference for those unfamiliar with f-string formatting.

2 of 3
12

As an addition to @cbilot 's answer.

You don't need to use slow python lambda functions to use special string formatting of expressions. Polars has a format function for this purpose:

df = pl.DataFrame({"bar": ["100", "250", "125", ""]})

df.with_columns(
    pl.format("This is {}!", pl.col("bar"))
)
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bar ┆ literal      β”‚
β”‚ --- ┆ ---          β”‚
β”‚ str ┆ str          β”‚
β•žβ•β•β•β•β•β•ͺ══════════════║
β”‚ 100 ┆ This is 100! β”‚
β”‚ 250 ┆ This is 250! β”‚
β”‚ 125 ┆ This is 125! β”‚
β”‚     ┆ This is !    β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
🌐
Medium
medium.com β€Ί @arkimetrix.analytics β€Ί part-3-phenomenal-python-polars-transform-recipes-data-type-operations-replace-extract-4aafa58bd046
Part 3. Python Polars - Data Type Operations, Replacements, Extractions, and Explosions | by Arkimetrix Analytics | Medium
April 30, 2023 - So, for example: df = df.collect() would query all available data. Before we get started with the transformations, your boss/customer complains that the β€˜Transaction_date’ is too long and needs to be shortened to β€˜date, and β€˜Ref’ should ...
🌐
Polars
docs.pola.rs β€Ί py-polars β€Ί html β€Ί reference β€Ί dataframe β€Ί api β€Ί polars.DataFrame.cast.html
polars.DataFrame.cast β€” Polars documentation
dtypes: Mapping[ColumnNameOrSelector | PolarsDataType, PolarsDataType] | PolarsDataType, *, strict: bool = True, ) β†’ DataFrame[source]# Cast DataFrame column(s) to the specified dtype(s). Parameters: dtypes Β· Mapping of column names (or selector) to dtypes, or a single dtype to which all columns will be cast. strict Β· Throw an error if a cast could not be done (for instance, due to an overflow). Examples Β·
🌐
Spark By {Examples}
sparkbyexamples.com β€Ί home β€Ί polars β€Ί polars dataframe.cast() method with examples
Polars DataFrame.cast() Method with Examples - Spark By {Examples}
February 18, 2025 - In Polars, the cast() method is used to change the data type of one or more columns in a DataFrame. It is useful when you need to convert columns to a
🌐
Polars
docs.pola.rs β€Ί py-polars β€Ί html β€Ί reference β€Ί dataframe β€Ί api β€Ί polars.DataFrame.dtypes.html
polars.DataFrame.dtypes β€” Polars documentation
>>> df = pl.DataFrame( ... { ... "foo": [1, 2, 3], ... "bar": [6.0, 7.0, 8.0], ... "ham": ["a", "b", "c"], ... } ... ) >>> df.dtypes [Int64, Float64, String] >>> df shape: (3, 3) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ foo ┆ bar ┆ ham β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ f64 ┆ str β”‚ β•žβ•β•β•β•β•β•ͺ═════β•ͺ═════║ β”‚ 1 ┆ 6.0 ┆ a β”‚ β”‚ 2 ┆ 7.0 ┆ b β”‚ β”‚ 3 ┆ 8.0 ┆ c β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
🌐
GitHub
github.com β€Ί pola-rs β€Ί polars β€Ί issues β€Ί 4982
Get column dtype in expression Β· Issue #4982 Β· pola-rs/polars
September 25, 2022 - For example, when applying a pl.duration to a pl.Date object, it converts it to a pl.Datetime object: import polars as pl from polars import col pl.DataFrame({'a': [date(2022, 1, 1)]}).select( (col('a') + pl.duration(days=1)) )
Author Β  pola-rs
🌐
Polars
docs.pola.rs β€Ί user-guide β€Ί concepts β€Ί data-types-and-structures
Data types and structures - Polars user guide
When creating a series, Polars will infer the data type from the values you provide. You can specify a concrete data type to override the inference mechanism: ... s1 = pl.Series("ints", [1, 2, 3, 4, 5]) s2 = pl.Series("uints", [1, 2, 3, 4, 5], dtype=pl.UInt64) print(s1.dtype, s2.dtype)
🌐
GitHub
github.com β€Ί pola-rs β€Ί polars β€Ί issues β€Ί 3089
handy functions to convert dtypes for columns between int/float and str Β· Issue #3089 Β· pola-rs/polars
April 7, 2022 - Maybe it's already there but I am not locating it, in which case I apologize for raising this request. I was looking for the documentation pretty thoroughly to see whether there would be a way to change the dtypes for the strings with nu...
Author Β  pola-rs
Find elsewhere
🌐
YouTube
youtube.com β€Ί shorts β€Ί 8JssZzM2b-M
Change Column Data Type In Polars | Python Tutorial - YouTube
In this video I show you how to change the data type of a column a Polars dataframe in Python#100daysofpython #coding #pythonforbeginners #pythontutorial #py...
Published Β  March 21, 2024
🌐
X
x.com β€Ί braaannigan β€Ί status β€Ί 1808070732150182009
Liam Brannigan on X: "The easiest way to change dtypes in Polars is with cast. We can pass individual column names in the dict, but we can also just pass a dtype-to-dtype mapping like in this example or a selector-to-dtype mapping to handle lots of columns very easily https://t.co/rbA6saleGC" / X
The easiest way to change dtypes in Polars is with cast. We can pass individual column names in the dict, but we can also just pass a dtype-to-dtype mapping like in this example or a selector-to-dtype mapping to handle lots of columns very easily
🌐
GitHub
github.com β€Ί pola-rs β€Ί polars β€Ί issues β€Ί 17620
Specifying NumPy dtype in to_numpy method Β· Issue #17620 Β· pola-rs/polars
July 14, 2024 - The "to_numpy" method in Polars currently converts a Series or DataFrame to a NumPy array, but it doesn't allow specifying the desired NumPy dtype during conversion. Please enhance the "to_numpy" method to specify the resulting dtype. # Example: series = pl.Series(name='data', values=['A', 'B', 'C'], dtype=pl.String) dtype = np.dtypes.StringDType(na_object=np.nan) # present conversion array = series.to_numpy().astype(dtype) # array(['A', 'B', 'C'], dtype=StringDType(na_object=nan)) # desired conversion array = series.to_numpy(dtype=dtype)
Author Β  pola-rs
🌐
Rho Signal
rhosignal.com β€Ί posts β€Ί polars-pandas-cheatsheet
Cheatsheet for Pandas to Polars | Rho Signal
December 22, 2024 - The output of aggregations in Pandas can be a Series whereas in Polars it is always a DataFrame. Where the output is a Series in Pandas there is a risk of the dtype being changed such as ints to floats.
🌐
Polars
docs.pola.rs β€Ί py-polars β€Ί html β€Ί reference β€Ί lazyframe β€Ί api β€Ί polars.LazyFrame.dtypes.html
polars.LazyFrame.dtypes β€” Polars documentation
>>> lf = pl.LazyFrame( ... { ... "foo": [1, 2, 3], ... "bar": [6.0, 7.0, 8.0], ... "ham": ["a", "b", "c"], ... } ... ) >>> lf.dtypes [Int64, Float64, String]
🌐
Pola-rs
pola-rs.github.io β€Ί polars-book β€Ί user-guide β€Ί expressions β€Ί casting
Casting - Polars documentation
Casting converts the underlying DataType of a column to a new one. Polars uses Arrow to manage the data in memory and relies on the compute kernels in the rust implementation to do the conversion.
🌐
Rust
docs.rs β€Ί polars β€Ί latest β€Ί polars β€Ί datatypes β€Ί index.html
polars::datatypes - Rust
At the moment Polars doesn’t include all data types available by Arrow. The goal is to incrementally support more data types and prioritize these by usability Β· See the AnyValue variants for the data types that are currently supported
🌐
Polars
docs.pola.rs β€Ί py-polars β€Ί html β€Ί reference β€Ί datatypes.html
Data types β€” Polars documentation
Base class for all Polars data types Β· Decimal 128-bit type with an optional precision and non-negative scale
🌐
Rho Signal
rhosignal.com β€Ί posts β€Ί polars-dtype-diet
Polars on a diet | Rho Signal
December 22, 2024 - Polars has a built in tool to go on a dtype diet. Call the shrink_dtype expression and it will convert the column to the dtype that requires the least amount of memory based on the data in the column. Both floats and integers default to 64-bit precision. In the example below from the API docs ...
🌐
Conterval
conterval.com β€Ί blog β€Ί override-data-types-in-polars
Changing data types while reading the file in polars - Conterval
November 13, 2025 - Most people read CSV files and then change the data type of columns. That is an amateur way of doing it. The professional approach is to do it all at once. Below is a dataframe showing a Polars function I covered each day in my 100DaysOfPolars.