1

I've the following array:

np.array([[0.07704314, 0.46752589, 0.39533099, 0.35752864],
          [0.45813299, 0.02914078, 0.65307364, 0.58732429],
          [0.32757561, 0.32946822, 0.59821108, 0.45585825],
          [0.49054429, 0.68553148, 0.26657932, 0.38495586]])

I want to find the minimum value in each row of the array. How can I achieve this?

Expected answer:

[[0.07704314 0.         0.         0.        ]
 [0.         0.02914078 0.         0.        ]
 [0.32757561 0          0.         0.        ]
 [0.         0.         0.26657932 0.        ]]

3 Answers 3

1

You can use np.where like so:

np.where(a.argmin(1)[:,None]==np.arange(a.shape[1]), a, 0)

Or (more lines but potentially more efficient):

out = np.zeros_like(a)
idx = a.argmin(1)[:, None]
np.put_along_axis(out, idx, np.take_along_axis(a, idx, 1), 1)
Sign up to request clarification or add additional context in comments.

Comments

0

IIUC first find out out the min value of each line , then we base on the min value mask all min value in original array as True, using multiple(matrix) , get what we need as result

np.multiply(a,a==np.min(a,1)[:,None])
Out[225]: 
array([[0.07704314, 0.        , 0.        , 0.        ],
       [0.        , 0.02914078, 0.        , 0.        ],
       [0.32757561, 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.26657932, 0.        ]])

1 Comment

You can use the keepdims=True kwarg here.
0

np.amin(a, axis=1) where a is your np array

2 Comments

I want to maintain the dimensions and indices. I want to fill 0 where the values are not minimum. Your solution gives a single dimension array of min values.
Yes, you are right. For some reason i didn't read the expected answer part. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.