5 ways to initialize NumPy array with NaN values

Numpy

In this post, we are going to learn how to initialize the NumPy array with NaN values. To do this we are going to use numpy. empty(),numpy.nan and fill() function.

1.Initialize NumPy array by NaN values using empty()


In this Python program, we are Initializing the NumPy array by NaN values using empty() function.

  • Creating an array using empty shape (2,3)
  • Using slicing to initializing nan in numpy array np.nan.

Python Program to Initialize NumPy array by NaN values

import numpy as np

 
nparr = np.empty((2,3))

nparr[:] = np.NaN
print(nparr)

Output

[[nan nan nan]
 [nan nan nan]]

2. Initialize NumPy array by NaN values using np.full()


In this Python program, we are initializing a NumPy array of shapes (2,3) and using numpy full() function to initialize the array with the same identical value.

Python Program to NumPy array by NAN values using np.full()

import numpy as np


nparr = np.full((2,3), np.nan)



print(nparr)

Output

[[nan nan nan]
 [nan nan nan]]

3. Initialize NumPy array by NaN values using np.fill()


In this Python program, we are checking how to initialize the NumPy array by nan values using np.fill(). Define a NumPy array of shape(2,2) and filling numpy array of nan Python.

Python Program To Initialize NumPy array using np.fill()

import numpy as np

nparr=np.empty((2,2))
nparr.fill(np.nan)

print(nparr)

Output

[[nan nan]
 [nan nan]]

4. Initialize NumPy array by NaN values Using title()


In this we are initializing the NumPy array by NAN values using numpy title() of shape of (2,3) and filling it with the same nan values.

  • Using numpy library as “import numpy as np”.
  • Calling the np.title() to fill numpy array of same identical values.
  • printing the result using print() method.

Python Program to initialize array by nan values using np.title()

import numpy as np

rows = 2
cols = 3


nparr = np.tile(np.nan, (rows,cols))


print(nparr)

Output

[[nan nan nan]
 [nan nan nan]]

5. Initialize NumPy array by NaN values Using np.one()


In this we are initializing the NumPy array by NAN values using numpy title() of shape of (2,3) and filling it with the same nan values.

  • Using numpy library as “import numpy as np”.
  • Calling the np.one() to fill numpy array of same identical values.
  • printing the result using print() method.

Python Program To initalize NumPy values Using np.one()

import numpy as np


nparr = np.nan * np.ones(shape=(3,2))


print(nparr)

Output

[[nan nan]
 [nan nan]
 [nan nan]]

Summary

In this post, how to initialize NumPy array with NaN values using numpy.empty(), numpy.fill(), numpy.full(), numpy.ones() function