Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Float to Int on certain columns in a data frame

Tags:

python

pandas

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...

like image 748
Rusty Avatar asked Nov 29 '16 00:11

Rusty


1 Answers

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.

like image 75
Abu Shoeb Avatar answered Oct 15 '22 17:10

Abu Shoeb