Rusty
Rusty

Reputation: 177

Converting Float to Int on certain columns in a data frame

I am trying to convert columns 0 to 4 and 6 to ints from there current float types.

I tried:

df[0:4,6].astype(int)

but of course this does not work...

Upvotes: 13

Views: 37386

Answers (2)

Abu Shoeb
Abu Shoeb

Reputation: 5153

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.

Upvotes: 7

piRSquared
piRSquared

Reputation: 294218

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

Upvotes: 15

Related Questions