VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-randomly-insert-nan-in-a-matrix-with-numpy-in-python/

⇱ How to randomly insert NaN in a matrix with NumPy in Python ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to randomly insert NaN in a matrix with NumPy in Python ?

Last Updated : 23 Jul, 2025

Prerequisites: Numpy

In this article, let's see how to generate a Python Script that randomly inserts Nan into a matrix using Numpy. Given below are 3 methods to do the same:

Method 1: Using ravel() function

ravel() function returns contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made only if needed.
Syntax :

numpy.ravel(array, order = 'C')

Approach:

  • Import module
  • Create data
  • Choose random indices to Nan value to.
  • Pass these indices to ravel() function
  • Print data

Example 1:

Output:

👁 Image

Example 2: Adding nan to but using randint function to create data. For using np.nan in randint function we must first convert the data into float as np.nan is of float type.

Output:

👁 Image

Method 2: Creating mask 

Creating a mask of boolean and applying that mask to the dataset can be one approach to produce the required result.

Approach:

  • Import module
  • Create data
  • Create mask
  • Shuffle the mask to randomly apply Nan values
  • Apply the mask to the data
  • Print data

Example :

Output:

👁 Image

Method 3: Using insert() 

Using insert() function will convert a whole row or a whole column to NaN. This function inserts values along the mentioned axis before the given indices.
Syntax :

numpy.insert(array, object, values, axis = None)

Approach:

  • Import module
  • Create data
  • Use insert Nan values
  • Print data

Example:

Output:

👁 Image
Comment