numpy modifies the specified value per line

Viewed 48

I don't want to use a loop to achieve this, wondering if there is a numpy method.

I want to modify the minimum or maximum value of each row to a specified value

Suppose it is changed to -1

I don't want to use a 'for' loop since there are millions of rows

arr = np.array([[1, 2, 3],
                [6, 5, 4],
                [7, 8, 9],
                [15, 12, 43],
                [2, 2, 2],
                [2, 2, 1],
                [1, 2, 1],
                ])
min_arr = np.min(arr, axis=1) # [ 1  4  7 12  2  1  1]


# result
[[-1  2  3]
 [ 6  5 -1]
 [-1  8  9]
 [15 -1 43]
 [-1 -1 -1]
 [ 2  2 -1]
 [-1  2 -1]]
1 Answers

Using numpy argmin() to find the indices:

Then use numpy put_along_axis() to update values with val (-1).

val = -1
arr_mins = np.expand_dims(np.argmin(arr, axis=1), axis=1)
np.put_along_axis(arr, arr_mins , val , axis=1)

The above code works if you want to replace just the first occurrence of the minimum value in each row.

If you want to replace multiple occurrences of the minimum value in each row, do the following:

arr_mins = np.argwhere(arr == np.expand_dims(np.min(arr, axis=1),axis=1))
rows = a [:,0]
cols = a [:,1]
arr[rows, cols] = -1

Sources:

How to make numpy.argmax return all occurrences of the maximum?

Get all column indices of equal to max and use them to index another array: numpy vs sparse csr_matrix

Related