Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 445
Steven01123581321 Avatar asked Nov 26 '25 12:11

Steven01123581321


1 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.]])
like image 132
Mustafa Aydın Avatar answered Nov 29 '25 01:11

Mustafa Aydın



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!