无法将ploat中的float转换为int

时间:2018-11-14 21:59:05

标签: python pandas int

我想将具有-1.0、0.0和Nans值的列转换为int。我已经尝试过pd.tonumericmyCol.astype

myCol = pd.to_numeric(myCol,downcast='signed', errors = 'coerce')
myCol.astype(np.int64, errors= 'ignore')

这些方法都不起作用。 所需的输入和输出

input: myCol = pd.Series([np.nan, 0.0, -1.0, 0.0, 0.0, 2.0])
output: Nan, 0, -1, 0, 0, 2

谢谢。

2 个答案:

答案 0 :(得分:0)

不幸的是,NaN本身就是一个浮点数(请检查IEEE 754浮点标准)。因此,除非您删除带有NaN的行,否则您向int的转换将始终失败!

否则,您使用astype的方法是正确的。

答案 1 :(得分:0)

您可以尝试创建字符串:

myCol.astype(str).str.split('.', expand=True)[0].tolist()

输出:

['nan', '0', '-1', '0', '0', '2']