Converting Float to Int on certain columns in a data frame

前端 未结 2 959
暖寄归人
暖寄归人 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.

    0 讨论(0)
  • 2021-01-17 19:31

    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})
    

    0 讨论(0)
提交回复
热议问题