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 th
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.
consider df
df = pd.DataFrame(np.random.rand(10, 10) * 10)
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})