带函数参数的Numpy最小值

2024-03-29 10:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以在应用函数后计算数组的最小索引值(即matlabfind的等价物)?你知道吗

换言之,考虑以下情况:

 a = [1,-3,-10,3]

 np.find_max(a,lambda x:abs(x)) 

应该返回2。你知道吗

显然,我可以为此编写一个循环,但我认为如果存在内置的numpy函数,那么使用它会更快。你知道吗


Tags: 方法lambda函数numpynp情况abs数组
1条回答
网友
1楼 · 发布于 2024-03-29 10:27:01

根据文档使用argmax

numpy.argmax(a, axis=None, out=None)

Returns the indices of the maximum values along an axis.

Parameters: a : array_like Input array. axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis. out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Returns: index_array : ndarray of ints Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. See also ndarray.argmax, argmin

amax The maximum value along a given axis. unravel_index Convert a flat index into an index tuple. Notes

In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.

import numpy as np

a = [1, -3, -10, 3]
print(np.argmax(np.abs(a)))

输出:

2

相关问题 更多 >