How to Convert Float to Int in a Pandas DataFrame
How can we cast a float
to an int
in a Pandas DataFrame column?
Cast with astype()
We can use astype()
to cast a Pandas object to a specified data type.
Suppose we have a column col
that is of type float
. We want to convert that to an int
type.
We can do this like so.
df['col'] = df['col'].astype(int)
Handle null
values
The above approach will lead to an error if there are any missing or null
values.
ValueError: Cannot convert NA to integer
In these cases, we’ll have to fill in the missing values. Let’s default any missing values to 0.0
.
df['col'] = df['col'].fillna(0.0).astype(int)