Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert polars dataframe column type from float64 to int64?

I have a polars dataframe, like:

import polars as pl
df = pl.DataFrame({"foo": [1.0, 2.0, 3.0], "bar": [11, 5, 8]})

How do I convert the first column to int64 type?
I was trying something like:

df.select(pl.col('foo')) = df.select(pl.col('foo')).cast(pl.Int64)

but it is not working.
In Pandas it was super easy:

df['foo'] = df['foo'].astype('int64')

Thanks.

like image 934
lmocsi Avatar asked Oct 12 '25 12:10

lmocsi


1 Answers

Select your col, cast it to (int64) and add it back to the original DataFrame with_columns.

df = df.with_columns(pl.col("foo").cast(pl.Int64))

Output :

print(df)

shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 11  │
│ 2   ┆ 5   │
│ 3   ┆ 8   │
└─────┴─────┘
like image 85
Timeless Avatar answered Oct 15 '25 19:10

Timeless