如何在Python的NumPy向量中找出小于1的最大值的索引?
解决NumPy中寻找小于1的最大值对应索引的问题
嘿,我懂你遇到的问题啦!你原来的代码返回空数组是因为整个数组的最大值是1.5,它并不满足小于1的条件,所以temp_res == temp_res.max()和temp_res < 1这两个条件没法同时成立。咱们换个思路,先锁定所有小于1的元素,再在这个子集里找最大值的索引就行。
下面给你两种实用的实现方式:
方法1:分步筛选+找索引
这种方法逻辑清晰,还能处理有多个相同最大值的情况(会返回所有对应的索引):
import numpy as np temp_res = [0.9, 0.8, 0.7, 0.99, 1.2, 1.5, 0.1, 0.5, 0.1, 0.01, 0.12, 0.56, 0.89, 0.23, 0.56, 0.78] temp_res = np.asarray(temp_res) # 1. 创建掩码,筛选出所有小于1的元素 mask = temp_res < 1 # 2. 从筛选后的元素中找到最大值 max_under_1 = temp_res[mask].max() # 3. 找到数组中等于这个最大值的所有索引 indices = np.where(temp_res == max_under_1) print(indices) # 输出: (array([3]),)
方法2:用argmax一步到位
如果只需要第一个出现的最大值索引,这种方法更简洁:
import numpy as np temp_res = [0.9, 0.8, 0.7, 0.99, 1.2, 1.5, 0.1, 0.5, 0.1, 0.01, 0.12, 0.56, 0.89, 0.23, 0.56, 0.78] temp_res = np.asarray(temp_res) # 把大于等于1的元素替换成负无穷,这样argmax会自动忽略它们 indices = np.argmax(np.where(temp_res < 1, temp_res, -np.inf)) print(indices) # 输出: 3
两种方法都能帮你得到想要的索引3,你可以根据自己的需求(是否需要多个索引)选择合适的方案~
内容的提问来源于stack exchange,提问作者Jose Ramon
相关产品推荐
相关产品推荐

