python - 在 numpy 数组中查找最后一个值

标签 python numpy

我有一个一维数组,想像这样找到最后一个值。

a = np.array([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1])
# find the index that value(7) last appear.
np.argwhere(a >= 7).max()
# output 10

但是它适用于一维数组,那么三维数组呢。

b = np.tile(a.reshape(15,1,1), reps=(1,30,30))
# now b is 3d array and i want to use same way to the axis = 0 in 3d array.
np.argwhere(b >= 7)
# return a 2d array. It's not what i need.

虽然我可以使用 'for' 循环另一个轴,但我想通过 numpy 有效地解决它。

最佳答案

首先,要获取最后一次出现的 7 的索引,您可以使用:

import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1])

indices = np.argwhere(a== 7)
last_index = indices[-1]
# 10

现在,如果您有一个 3 维数组,您仍然可以使用 np.argwhere 来获取 7 的出现次数,但每次出现都将出现在 3 维空间中。要获得最后一次出现的 7,您将再次编写

b = np.tile(a.reshape(17,1,1), reps=(1,30,30))
np.argwhere(b==7)[-1]
# [10 29 29]

返回的正是您所期望的。

关于python - 在 numpy 数组中查找最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944060/

相关文章:

numpy - 使用 2D 整数数组索引 3D 数组的最后一个维度

opencv - Numpy 翻转图像 + cv2.filter2D = 断言失败?

python - 将 np.where 与索引一起使用

python - 如何制作将多个模式匹配到同一索引的python正则表达式

python - 使用 Django 1.9 时,当我删除模型对象时,如何让 Django 删除文件?

python - PDF 出血检测

python - 如何计算数字数组的对数阶乘

python - 如何在不使用 numpy/pandas 的情况下处理 csv 文件中的缺失数据?

python - 谷歌云端点: Picturesque App

python - 一列的行号,但随后使用另一列重新排序