Converting Float to Int on certain columns in a data frame

前端 未结 2 960
暖寄归人
暖寄归人 2021-01-17 18:45

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

2条回答
  •  逝去的感伤
    2021-01-17 19:13

    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.

提交回复
热议问题