ValueError: cannot convert float NaN to integer"
ValueError: cannot convert float NaN to integer"
在下面的代码中,我有数据框,我希望如果某个条件满足该条件恰好被 nan 行替换的行,但它不起作用,当我试图查看它是如何工作时逐一我收到错误
```{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"}```
那是因为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)
在下面的代码中,我有数据框,我希望如果某个条件满足该条件恰好被 nan 行替换的行,但它不起作用,当我试图查看它是如何工作时逐一我收到错误
```{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"}```
那是因为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)