| by msbeta | No comments

找出Numpy Array中的元素的最小值及它的索引

1.numpy array的最小值

numpy中提供了numpy.amin()函数,用来找出numpy array中沿着指定轴的最小值。函数的原型如下:

numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

参数:
a: 待查询的数组数据;
axis: 指定查询的数据axis,如果不指定axis,模式查找所有元素的最小值;

以如下numpy array为例:

arr = numpy.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])

使用numpy.amin()查找最小值:

# Get the minimum element from a Numpy array
min_element = numpy.amin(arr)

print('minimum element from numpy array : ', min_element)

程序输出:

minimum element from numpy array :  11

2.找出numpy array最小值的索引

np.where可以找出numpy array中最小值的索引。

# Get the indices of minimum element in numpy array
result = numpy.where(arr == numpy.amin(arr))

print('returned tuple of arrays: ', result)
print('list of Indices of minimum element:', result[0])

输出:

returned result: (array([0, 8], dtype=int32),)

list of indices of minimum element: [0 8]

3.找出二维numpy array的最小值

先定义一个二维numpy array。

# Create a 2D Numpy array from list of lists
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])

使用numpy.amin()函数获取二维numpy array的最小值。

# Get the minimum value from complete 2D numpy array
minValue = numpy.amin(arr2D)

numpy.amin()会返回二维numpy array的所有行和所有列的最小值。上述代码的输出:

11

使用numpy.amin()计算二维数组每一列的最小值。

# Get the minimum values of each column i.e. along axis 0
minInColumns = numpy.amin(arr2D, axis=0)

print('min value of every column: ', minInColumns)

程序输出:

min value of every column:  [11 12 11]

使用numpy.amin()计算二维数组每一行的最小值。

# Get the minimum values of each row i.e. along axis 1
minInRows = numpy.amin(arr2D, axis=1)

print('min value of every row: ', minInRows)

程序输出:

min value of every row:  [11 14 11 12]

4. 找出二维numpy array最小值的索引

# Find index of minimum value from 2D numpy array
result = numpy.where(arr2D == numpy.amin(arr2D))

print('tuple of arrays returned : ', result)
print('list of coordinates of minimum value in numpy array : ')

# zip the 2 arrays to get the exact coordinates
listOfCordinates = list(zip(result[0], result[1]))

# travese over the list of cordinates
for cord in listOfCordinates:
    print(cord)

程序输出:

tuple of arrays returned :  (array([0, 2], dtype=int32), array([0, 2], dtype=int32))

list of coordinates of minimum value in numpy array : 
(0, 0)
(2, 2)

5. numpy array中包含nan数据

当numpy array中包含nan时,numpy.amin()会返回nan。

arr = numpy.array([11, 12, 13, 14, 15], dtype=float)
arr[3] = numpy.NaN
print('min element from numpy array : ', numpy.amin(arr))

输出:

min element from numpy array :  nan

如果要忽略NaN数据,寻找除NaN之外的所有其它的值的最小值,可以使用numpy.nanmin()函数,或者使用numpy.amin的where参数。

numpy.amin(arr, where=~numpy.isnan(arr), initial=10)

参考材料

https://thispointer.com/numpy-amin-find-minimum-value-in-numpy-array-and-its-index/

https://numpy.org/doc/stable/reference/generated/numpy.amin.html

发表评论