Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: ValueError: cannot convert float NaN to integer (Python)

Tags:

python

numpy

I want to insert NaN at specific locations in A. However, there is an error. I attach the expected output.

import numpy as np
from numpy import NaN

A = np.array([10, 20, 30, 40, 50, 60, 70])
C=[2,4]

A=np.insert(A,C,NaN,axis=0)
print("A =",[A])

The error is

<module>
    A=np.insert(A,C,NaN,axis=0)

  File "<__array_function__ internals>", line 5, in insert

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4678, in insert
    new[tuple(slobj)] = values

ValueError: cannot convert float NaN to integer

The expected output is

[array([10, 20,  NaN, 30, 40,  NaN, 50, 60, 70])]
like image 780
Wiz123 Avatar asked Oct 17 '25 19:10

Wiz123


1 Answers

Designate a type for your array of float32 (or float16, float64, etc. as appropriate)

import numpy as np

A = np.array([10, 20, 30, 40, 50, 60, 70], dtype=np.float32)
C=[2,4]

A=np.insert(A,C,np.NaN,axis=0)
print("A =",[A])

A = [array([10., 20., nan, 30., 40., nan, 50., 60., 70.], dtype=float32)]

like image 125
jonsca Avatar answered Oct 19 '25 09:10

jonsca