Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找以numpy排除零值为单位的最大值索引_Python_Numpy - Fatal编程技术网

Python 查找以numpy排除零值为单位的最大值索引

Python 查找以numpy排除零值为单位的最大值索引,python,numpy,Python,Numpy,我有以下要点: e = np.array([0, -1.3, 0, -3.9, 0, -0.9, 0]) 我想查找列表中最大值的索引,但不包括0 下面的代码示例返回列表中的第一个元素,因为其值为0 result = np.argmax(e) print(result) 但我不想考虑最大值的零点: 预期结果应为5,这是-0.9值元素的索引 我不想编写将在列表上迭代运行的代码 有什么想法吗?一个简单的解决方案是用-np.inf替换0 a[a == 0] = -np.inf np.argmax(a

我有以下要点:

e = np.array([0, -1.3, 0, -3.9, 0, -0.9, 0])
我想查找列表中最大值的索引,但不包括0

下面的代码示例返回列表中的第一个元素,因为其值为0

result = np.argmax(e)
print(result)

但我不想考虑最大值的零点:

预期结果应为
5
,这是
-0.9
值元素的索引

我不想编写将在列表上迭代运行的代码


有什么想法吗?

一个简单的解决方案是用-np.inf替换0

a[a == 0] = -np.inf
np.argmax(a)
>>> 5

一种可能的办法是:

import numpy as np

e = np.array([0, -1.3, 0, -3.9, 0, -0.9, 0])

result = np.nanargmax(np.where(e != 0, e, np.nan))
print(result)
输出

5
请注意,这不会更改输入数组(在本例中为
e