In Polars, you can use the cast() method with pl.Int64 to convert a float column to an integer type, ensuring efficient transformation of floating-point numbers into whole numbers. This function enables you to change a column's data type. However, the conversion outcome depends on whether you truncate or round the values before casting. In this article, I will explain how to convert a float column to an integer type using Polars.
Key Points –
- Casting a float to an integer in Polars truncates (removes) the decimal part instead of rounding.
- Use
cast(pl.Int64)or other integer types to convert a float column to an integer. - Use
round(0)to ensure values are rounded instead of truncated before conversion. - Choose smaller integer types (
Int8,Int16,Int32) instead ofInt64to reduce memory usage. - Apply casting to multiple float columns using
with_columns()for batch processing. - Always verify data types after conversion using
df.dtypesto ensure expected changes. - Memory-efficient integer types should be chosen based on the data range to avoid overflow.
- By default, casting removes the decimal part without rounding (e.g.,
3.8→3).
<a id="h-usage-of-polars-float-to-integer"></a>
Usage of Polars Float to Integer
You can easily convert a float column to an integer type using the cast() method in polars. This function allows efficient type conversion, enabling you to change a column’s data type to any desired format, including integers. To perform the conversion, apply cast(pl.Int64) to the target column.
To run some examples of converting polars cast float to integer, 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 convert float columns to integers in Polars without rounding (by truncating the decimal part), use the cast(pl.Int64) method. This allows you to transform float columns, such as Fees and Discount, into integers within a Polars DataFrame.
# Convert float columns to integers
df2 = df.with_columns(
df["Fees"].cast(pl.Int64),
df["Discount"].cast(pl.Int64))
print("After Converting Float Columns to Integers:\n", df2)
Here,
with_columns()is used to create a new DataFrame with the modified column types.pl.col("Fees").cast(pl.Int64)converts the"Fees"column fromf64(float) toInt64(integer).pl.col("Discount").cast(pl.Int64)converts theDiscountcolumn toInt64.
<a id="h-rounding-before-conversion"></a>
Rounding Before Conversion
To round float values before converting them to integers, use round(0).cast(pl.Int64). This ensures proper rounding rather than truncation. When converting float (f64) columns to integers (i64), rounding the values first helps prevent data loss. Polars also offers various rounding methods before conversion.
# Round before converting float columns to integers
df2 = df.with_columns(
df["Fees"].round(0).cast(pl.Int64),
df["Discount"].round(0).cast(pl.Int64))
print("DataFrame after Rounding and Converting Float Columns to Integers:\n", df2)
# Output:
# DataFrame after Rounding and Converting Float Columns to Integers:
# shape: (5, 4)
┌─────────┬───────┬──────────┬──────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 │
╞═════════╪═══════╪══════════╪══════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000 │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300 │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1001 │
│ Python ┆ 24001 ┆ 40days ┆ 1200 │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500 │
└─────────┴───────┴──────────┴──────────┘
Here,
round(0)rounds values to the nearest integer.cast(pl.Int64)converts rounded values to integers.with_columns()creates a new DataFrame with the modified column types.
<a id="h-cast-single-column-from-float-to-integers"></a>
Cast Single Column from Float to Integers
If you need to convert just one column from float (f64) to integer (i64), you can use the with_columns() method and apply cast(pl.Int64) to that specific column.
# Convert only 'Fees' column to integer
df2 = df.with_columns(df["Fees"].cast(pl.Int64))
print("DataFrame after Converting 'Fees' Column to Integer:\n", df2)
# Output:
# DataFrame after Converting 'Fees' Column to Integer:
# shape: (5, 4)
┌─────────┬───────┬──────────┬──────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ f64 │
╞═════════╪═══════╪══════════╪══════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000.1 │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300.15 │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000.5 │
│ Python ┆ 24000 ┆ 40days ┆ 1200.22 │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500.2 │
└─────────┴───────┴──────────┴──────────┘
Here,
df["Fees"].cast(pl.Int64)converts only theFeescolumn toInt64, leaving other columns unchanged.with_columns(…)returns a new DataFrame with the modified column.
<a id="h-using-unsigned-integer-types"></a>
Using Unsigned Integer Types
If you want to use unsigned integer types (UInt64, UInt32, etc.) in Polars, you can explicitly cast your float column to an unsigned integer type. This ensures that all values are non-negative and efficiently stored.
# Convert 'Fees' column to Unsigned Integer (UInt64) after rounding
df2 = df.with_columns(df["Fees"].round(0).cast(pl.UInt64))
print("DataFrame after Converting 'Fees' Column to Unsigned Integer:\n", df2)
# Output:
# DataFrame after Converting 'Fees' Column to Unsigned Integer:
# shape: (5, 4)
┌─────────┬───────┬──────────┬──────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u64 ┆ str ┆ f64 │
╞═════════╪═══════╪══════════╪══════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000.1 │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300.15 │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000.5 │
│ Python ┆ 24001 ┆ 40days ┆ 1200.22 │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500.2 │
└─────────┴───────┴──────────┴──────────┘
Here,
df["Fees"].round(0)rounds the values before conversion to prevent truncation.cast(pl.UInt64)converts theFeescolumn to an unsigned integer (UInt64), ensuring all values are non-negative.with_columns()returns a new DataFrame with the modified column.
<a id="h-using-a-smaller-integer-type-for-memory-efficiency"></a>
Using a Smaller Integer Type for Memory Efficiency
To enhance memory efficiency, consider casting the column to Int32 or even Int16, depending on the value range. Using a smaller integer type in Polars helps optimize memory usage while storing numerical data effectively. Instead of the default Int64, you can use Int32, Int16, or Int8 when the values fall within their respective limits.
# Convert 'Fees' column to Int32 for memory efficiency
df2 = df.with_columns(df["Fees"].cast(pl.Int32))
print("DataFrame after Converting 'Fees' Column to Int32:\n", df2)
# Output:
# DataFrame after Converting 'Fees' Column to Int32:
# shape: (5, 4)
┌─────────┬───────┬──────────┬──────────┐
│ Courses ┆ Fees ┆ Duration ┆ Discount │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i32 ┆ str ┆ f64 │
╞═════════╪═══════╪══════════╪══════════╡
│ Spark ┆ 22000 ┆ 30days ┆ 1000.1 │
│ PySpark ┆ 25000 ┆ 50days ┆ 2300.15 │
│ Hadoop ┆ 23000 ┆ 35days ┆ 1000.5 │
│ Python ┆ 24000 ┆ 40days ┆ 1200.22 │
│ Pandas ┆ 26000 ┆ 55days ┆ 2500.2 │
└─────────┴───────┴──────────┴──────────┘
<a id="h-casting-a-column-with-negative-floats"></a>
Casting a Column with Negative Floats
When casting a column with negative floats to integers in Polars, you should consider whether to round the values before conversion or simply truncate them. By default, casting from float to integer truncates towards zero, meaning it removes the decimal part without rounding.
import polars as pl
# Define the dictionary with negative float values
data = {
'Courses': ["Spark", "PySpark", "Hadoop", "Python", "Pandas"],
'Fees': [22000.30, -25000.40, 23000.20, -24000.50, 26000.10],
'Discount': [-1000.10, 2300.15, -1000.5, 1200.22, -2500.20]
}
# Create Polars DataFrame
df = pl.DataFrame(data)
# Convert 'Fees' column to integer
df2 = df.with_columns(df["Fees"].cast(pl.Int64))
print("DataFrame after Casting 'Fees' Column to Integer:\n", df2)
If you want to round negative floats before casting to integers in Polars, you can use the round(0) method before applying cast(pl.Int64). This ensures that values are rounded to the nearest integer instead of being truncated.
# Round 'Fees' column before casting to integer
df2 = df.with_columns(df["Fees"].round(0).cast(pl.Int64))
print("DataFrame after Rounding and Casting 'Fees' Column:\n", df2)
# Output:
# DataFrame after Casting 'Fees' Column to Integer:
# shape: (5, 3)
┌─────────┬────────┬──────────┐
│ Courses ┆ Fees ┆ Discount │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞═════════╪════════╪══════════╡
│ Spark ┆ 22000 ┆ -1000.1 │
│ PySpark ┆ -25000 ┆ 2300.15 │
│ Hadoop ┆ 23000 ┆ -1000.5 │
│ Python ┆ -24000 ┆ 1200.22 │
│ Pandas ┆ 26000 ┆ -2500.2 │
└─────────┴────────┴──────────┘
<a id="h-conclusion"></a>
Conclusion
In conclusion, converting floats to integers in Polars is simple using the cast() method with pl.Int64. This approach changes the column’s data type, transforming float values into integers. Using the with_columns() method, you can either update an existing column or create a new one with the converted values.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Convert Polars Cast Float to String
- Convert Polars Cast Int to String
- Convert Polars Cast String to Float
- Polars Convert Cast String to Integer
- Polars DataFrame count() Function
- Polars DataFrame limit() Method
- Polars DataFrame row() Usage & Examples
- Polars DataFrame median() Usage & Examples
- Polars.DataFrame.mean() – Explained by Examples
- Polars DataFrame partition_by() Usage & Examples
<a id="h-references"></a>
