How to Create NumPy Matrix Filled with NaNs?

In this tutorial, we will learn how to create a NumPy matrix filled with NaN values? By Pranit Sharma Last updated : May 24, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell.

Creating NumPy Matrix Filled with NaNs

There are two ways to create NumPy matrix filled with NaNs:

  1. Create an empty matrix and fill it with NaNs
  2. Create matrix using numpy.full() method

1) Create an empty matrix and fill it with NaNs

In this way, to create a NumPy matrix filled with NaNs, you can simply create an empty matrix by using the numpy.empty() method by passing the number of rows and columns and then fill the NaN values using the numpy.fill() method.

Example 1: Create NumPy Matrix Filled with NaNs

# Import numpy
import numpy as np

# Create an empty matrix
arr = np.empty((3,3))

# Fill it with NaNs
arr.fill(np.NaN)

# Display the matrix
print("The matrix is:\n",arr,"\n")

Output

The matrix is:
 [[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

2) Create matrix using numpy.full() method

You can also create a NumPy matrix filled with NaNs by using the numpy.full() method by specifying the number of rows and columns along with the numpy.NaN.

Example 2: Create NumPy Matrix Filled with NaNs

# Import numpy
import numpy as np

# Create matrix filled with NaNs
arr = np.full((3,3),np.NaN)

# Display the matrix
print("The matrix is:\n",arr,"\n")

Output

The matrix is:
 [[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.