【问题标题】:how to get the index of the largest n values in a multi-dimensional numpy array [duplicate]如何获取多维numpy数组中最大n值的索引[重复]
【发布时间】:2015-06-30 06:40:12
【问题描述】:

我想获取多维 numpy 数组中最大 n 值的索引。为了获得一维 numpy 数组中最大 n 值的索引,我找到了this。在 python 的交互式 shell 中测试后,bottleneck.argpartsort 似乎无法影响多维 numpy 数组。为了获取多维 numpy 数组中最大值的索引,我找到了this。它不能得到最大的n。我可以给出的方法是将多维 numpy 数组转换为{value:index}(元组存在的索引)的列表,然后按值对列表进行排序,并获取它的索引。有什么更简单或更高性能的吗?

【问题讨论】:

  • reshape 到一维,然后搜索,然后通过涉及reshape 之前的维度的算术计算得到原始索引?
  • 也许flatten()原始数组,然后使用您的一维解,最后使用原始形状计算真正的nD索引?
  • 第二个链接有什么问题?你能告诉我们这个多维数组的一部分吗?我不明白为什么它不应该工作......
  • @plonser第二个链接只返回多维numpy数组最大值的索引

标签: python arrays algorithm numpy multidimensional-array


【解决方案1】:

我无权访问bottleneck,因此在本例中我使用的是argsort,但您应该能够以同样的方式使用它:

#!/usr/bin/env python
import numpy as np
N = 4
a = np.random.random(20).reshape(4, 5)
print(a)

# Convert it into a 1D array
a_1d = a.flatten()

# Find the indices in the 1D array
idx_1d = a_1d.argsort()[-N:]

# convert the idx_1d back into indices arrays for each dimension
x_idx, y_idx = np.unravel_index(idx_1d, a.shape)

# Check that we got the largest values.
for x, y, in zip(x_idx, y_idx):
    print(a[x][y])

【讨论】:

  • 使用argpartition 而不是argsort,你会赢得我的支持。 ;-)
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 2017-03-27
  • 2011-04-04
  • 1970-01-01
相关资源
最近更新 更多