简体   繁体   English

在数据框中的某些列上将 Float 转换为 Int

[英]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.我正在尝试将 0 到 4 和 6 列从当前的浮点类型转换为整数。

I tried:我试过:

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

but of course this does not work...但这当然行不通......

consider df考虑df

df = pd.DataFrame(np.random.rand(10, 10) * 10)

在此处输入图片说明

use np.r_ to get slc使用np.r_获取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})

在此处输入图片说明

I was getting an error as some of my column values were NaN which obviously can not be converted to int .我收到一个错误,因为我的一些列值是NaN显然无法转换为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 .因此,更好的方法是在转换datatype之前处理NaN并避免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填充NaN ,然后转换为所需的datatype ,在本例中为int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM