find infinity values and replace with maximum per vector in a numpy array

Viewed 307

Suppose I have the following array with shape (3, 5) :

array = np.array([[1, 2, 3, inf, 5],
                    [10, 9, 8, 7, 6],
                    [4, inf, 2, 6, inf]])

Now I want to find the infinity values per vector and replace them with the maximum of that vector, with a lower limit of 1.

So the output for this example shoud be:

array_solved = np.array([[1, 2, 3, 5, 5],
                    [10, 9, 8, 7, 6],
                    [4, 6, 2, 6, 6]])

I could do this by looping over every vector of the array and apply:

idx_inf = np.isinf(array_vector)
max_value = np.max(np.append(array_vector[~idx_inf], 1.0))
array_vector[idx_inf] = max_value

But I guess there is a faster way.

Anyone an idea?

2 Answers

One way is to first convert infs to NaNs with np.isinf masking and then NaNs to max values of rows with np.nanmax:

array[np.isinf(array)] = np.nan
array[np.isnan(array)] = np.nanmax(array, axis=1)

to get

>>> array

array([[ 1.,  2.,  3.,  5.,  5.],
       [10.,  9.,  8.,  7.,  6.],
       [ 4., 10.,  2.,  6.,  6.]])
import numpy as np

array = np.array([[1, 2, 3, np.inf, 5],
                    [10, 9, 8, 7, 6],
                    [4, np.inf, 2, 6, np.inf]])

n, m = array.shape
array[np.isinf(array)] = -np.inf
mx_array = np.repeat(np.max(array, axis=1), m).reshape(n, m)
ind = np.where(np.isinf(array))
array[ind] = mx_array[ind]

Output array:

array([[ 1.,  2.,  3.,  5.,  5.],
       [10.,  9.,  8.,  7.,  6.],
       [ 4.,  6.,  2.,  6.,  6.]])
Related