ValueError:无法将float NaN转换为整数”

时间:2020-04-30 14:05:33

标签: python machine-learning pycharm supervised-learning

在下面的代码中,我有数据框,我希望如果某个条件满足该条件的行,该条件恰好被nan row替换,但它不起作用,并且当我尝试查看它如何工作时遇到错误

```{x_r = data.drop(['y'], axis="columns")
    x_nan = np.empty((len(x_r), len(x_r.columns)))
    x_nan[:] = np.nan
    x_2 = x_r.values
    for i in range(0, len(x_r)):
    if y[i] < q_:
    x_2[i, :] = x_nan[i, :]}```

然后搜索单个路径

```{x_2[0,0]=x_nan[0,0]}```

它给了我以下错误:

 ```{"exec(code_obj, self.user_global_ns, self.user_ns)
   File "<ipython-input-42-d9db7fa21a9c>", line 1, in <module>
   x_2[0,0]=x_nan[0,0]
   ValueError: cannot convert float NaN to integer"}```

1 个答案:

答案 0 :(得分:0)

这是因为nan被认为是float数组的特殊字符(一种特殊的float),并且显然您的x_2数组是int类型;和nan无法转换为int以适合您的数组。

一种解决方法可能是将数组转换为浮点数:

>>>import numpy as np
>>>a = np.array([[1,2,3], [4,5,6]])
>>>a
array([[1, 2, 3],
       [4, 5, 6]])

>>>a[0,0] = np.nan
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-43-8e6dceaece5a> in <module>
----> 1 a[0,0] = np.nan

ValueError: cannot convert float NaN to integer

>>>a = a.astype('float32')
>>>a[0,0] = np.nan
>>>a
array([[nan,  2.,  3.],
   [ 4.,  5.,  6.]], dtype=float32)