Skip to content
Advertisement

How to replace values in a np 2d array based on condition for every row

I have a numpy 2d array (named lda_fit) with probabilities, where I want to replace the probabilities with 0 or 1, based on the max value in each line.

JavaScript

So after all the first line should look like [0,1,0,0], the second like [1,0,0,0] and so on. I have tried, and this works, but only for a given threshold (0.5):

JavaScript

But as I might not have the largest value being greater than 0.5, I want to specify a new threshold for each line. Unfortunately this gives me the max value of the whole array.

JavaScript

Advertisement

Answer

You can use np.max with specifying axis:

JavaScript

Note: if there is more than one max in a row, it will return 1 for all of them. For alternative solution follow the next method.

output for example input in question:

JavaScript

In case of multiple max in a row, if you want to have only first one as 1 and the rest of max as 0, you can use argmax:

JavaScript

or equally:

JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement