Replace np.inf values of a matrix with corresponding values of second matrix in Python

By IncludeHelp Last updated : November 25, 2023

Problem statement

Suppose that we are given two NumPy matrices, one with some np.inf values and the other with integers, write a Python program to replace the np.inf values with corresponding values of the second matrix.

Solution approach

To replace np.inf values of a matrix with corresponding values of the second matrix, first create a Boolean mask for the first matrix using the np.isinf() method to identify the positions of positive infinity values, and then use the & operator to only select the elements that are strictly greater than zero (to avoid replacing -np.inf values). Now, use the Boolean mask to replace the positive infinity values in the first matrix with the corresponding values from the second matrix. Finally, print the result.


In this example, there are two matrices a and b, a has some np.inf values whereas b has all integer values, and we are replacing np.inf values in matrix a with the corresponding values of matrix b.

# Importing numpy librray
import numpy as np

# Creating two matrices
a = np.array([[1, 2, np.inf], [4, np.inf, 6], [7, 8, 9]])
b = np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]])

# Printing matrices
print("Matrix (a):\n", a, "\n")
print("Matrix (b):\n", b, "\n")

# Creating a boolean mask for matix "a"
mask = np.isinf(a) & (a > 0)

# Use the boolean mask to replace np.inf values
# in "a" with the corresponding values from "b"
a[mask] = b[mask]

# Print the matrix "a"
print("Updated matrix (a):\n", a)


The output of the above example is:

Matrix (a):
 [[ 1.  2. inf]
 [ 4. inf  6.]
 [ 7.  8.  9.]] 

Matrix (b):
 [[10 11 12]
 [13 14 15]
 [16 17 18]] 

Updated matrix (a):
 [[ 1.  2. 12.]
 [ 4. 14.  6.]
 [ 7.  8.  9.]]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.