如何获得最大的n个值的指数多维数组numpy的 [英] how to get the index of the largest n values in a multi-dimensional numpy array

查看:1599
本文介绍了如何获得最大的n个值的指数多维数组numpy的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得最大的n个值的指数多维数组numpy的。为了获得最大的n个值的指数在一维数组numpy的,我发现<一个href=\"http://stackoverflow.com/questions/10337533/a-fast-way-to-find-the-largest-n-elements-in-an-numpy-array\">this.在Python交互式shell中试验后,似乎 bottleneck.argpartsort 无法多维数组numpy的影响上。对于多维数组numpy的获得最大价值的指数,我发现<一个href=\"http://stackoverflow.com/questions/3584243/python-get-the-position-of-the-biggest-item-in-a-numpy-array\">this.它不能得到最大的n个。我可以给的方法是多维numpy的数组转换为的列表:(由一个元组指标present){价值指数} ,然后排序列表由值,并得到索引它。有没有什么更容易或更表现?

I want to get the index of the largest n values in a multi-dimensional numpy array. For get the index of the largest n values in a one-dimensional numpy array, i found this. After test in interactive shell in python, it seems that bottleneck.argpartsort can't effect on multi-dimensional numpy array. For get the index of the largest value in a multi-dimensional numpy array, i found this. It can't get the largest n. The method that i can give is translate the multi-dimensional numpy array to a list of {value:index}(index present by a tuple), and then sort the list by the value, and get the index for it. Is there anything more easier or more performance?

推荐答案

我没有访问瓶颈,所以在这个例子中我使用 argsort ,但你应该能够以同样的方式使用它:

I don't have access to bottleneck, so in this example I am using argsort, but you should be able to use it in the same way:

#!/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])

这篇关于如何获得最大的n个值的指数多维数组numpy的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆