简体   繁体   中英

How to find minimum value in each row while keeping array dimensions same using numpy?

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.        ]]

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)

np.amin(a, axis=1)其中 a 是您的 np 数组

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.        ]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM