0

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"}```
Hanan
  • 33
  • 1
  • 5
  • Does this answer your question? [Pandas: ValueError: cannot convert float NaN to integer](https://stackoverflow.com/questions/47333227/pandas-valueerror-cannot-convert-float-nan-to-integer) – Amit Gupta Apr 30 '20 at 14:29
  • https://stackoverflow.com/questions/47333227/pandas-valueerror-cannot-convert-float-nan-to-integer – Amit Gupta Apr 30 '20 at 14:29

1 Answers1

0

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)
TitoOrt
  • 1,265
  • 1
  • 11
  • 13