[英]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...但这当然行不通......
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.