Converting Float to Int on certain columns in a data frame

consider df

df = pd.DataFrame(np.random.rand(10, 10) * 10)

enter image description here

use np.r_ to get slc

slc = np.r_[0:4, 6]
df[slc] = df[slc].astype(int)
df

or pass a dictionary of types with keys as column names

df.astype({c: int for c in slc})

enter image description here


I was getting an error as some of my column values were NaN which obviously can not be converted to int. So a better approach would be to handle NaN before converting the datatype and avoid ValueError: Cannot convert non-finite values (NA or inf) to integer.

df['col_name'] = df['col_name'].fillna(0).astype(int)

This fills NaN with 0 and then converts to the desired datatype which is int in this case.

Tags:

Python

Pandas