简体   繁体   中英

How can I get the row and column number of a numpy 2d array meeting a specified condition?

How can I get the row and column number of a numpy 2d array meeting a specified condition? For example, I have a 2d array (all float numbers) and I want to get the location (row and column index) where the minimum or maximum values is.

You can use np.where() as in the following example:

In [46]: arr = np.arange(10, dtype=float32).reshape(5, 2)

In [47]: arr
Out[47]: 
array([[ 0.,  1.],
       [ 2.,  3.],
       [ 4.,  5.],
       [ 6.,  7.],
       [ 8.,  9.]], dtype=float32)

# get row and column index of minimum value in arr
In [48]: np.where(arr == arr.min())
Out[48]: (array([0]), array([0]))

# get the indices of maximum element in arr
In [49]: np.where(arr == arr.max())
Out[49]: (array([4]), array([1]))

The above approach also works even if you have multiple minimum/maximum values in your array.

In [59]: arr
Out[59]: 
array([[ 0.,  0.],
       [ 2.,  3.],
       [ 4.,  5.],
       [ 6.,  7.],
       [ 9.,  9.]], dtype=float32)

In [60]: np.where(arr == arr.max())
Out[60]: (array([4, 4]), array([0, 1]))  # positions: (4,0) and (4,1)

In [61]: np.where(arr == arr.min())
Out[61]: (array([0, 0]), array([0, 1]))  # positions: (0,0) and (0,1)

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