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
```{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; and nan
cannot be converted to int
to fit into your array.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.