简体   繁体   English

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

[英]ValueError: cannot convert float NaN to integer"

in the following code, I have data frame and I want that if a certain condition satisfied the row where this condition happens to be replaced by nan row but it doesn't work and when I tried to see how it works case by case I got the error在下面的代码中,我有数据框,我希望如果某个条件满足该条件恰好被 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, :]}```

then for the individual trail然后对于个人踪迹

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

and it gave me the following error:它给了我以下错误:

 ```{"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"}```

That is because nan is recognised as a special character for float arrays (a sort of special float ), and apparently your x_2 array is int type;那是因为nan被认为是 float arrays 的特殊字符(一种特殊的float ),显然您的x_2数组是int类型; and nan cannot be converted to int to fit into your array.并且nan不能转换为int以适合您的数组。

A workaround could be casting your array into floats:一种解决方法可能是将您的数组转换为浮点数:

>>>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)

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

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