简体   繁体   English

如何获得满足指定条件的numpy 2d数组的行号和列号?

[英]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? 如何获得满足指定条件的numpy 2d数组的行号和列号? 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: 您可以在以下示例中使用np.where()

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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