[英]Iterate over numpy array in a specific order based on values
I want to iterate over a numpy array starting at the index of the highest value working through to the lowest value 我想迭代一个numpy数组,从最高值的索引开始到最低值
import numpy as np #imports numpy package
elevation_array = np.random.rand(5,5) #creates a random array 5 by 5
print elevation_array # prints the array out
ravel_array = np.ravel(elevation_array)
sorted_array_x = np.argsort(ravel_array)
sorted_array_y = np.argsort(sorted_array_x)
sorted_array = sorted_array_y.reshape(elevation_array.shape)
for index, rank in np.ndenumerate(sorted_array):
print index, rank
I want it to print out: 我希望它打印出来:
index of the highest value index of the next highest value index of the next highest value etc 下一个最高值的下一个最高值索引的最高值索引的索引等
Try this: 尝试这个:
from operator import itemgetter
>>> a = np.array([[2, 7], [1, 4]])
array([[2, 7],
[1, 4]])
>>> sorted(np.ndenumerate(a), key=itemgetter(1), reverse=True)
[((0, 1), 7),
((1, 1), 4),
((0, 0), 2),
((1, 0), 1)]
you can iterate this list if you so wish. 如果您愿意,可以迭代此列表。 Essentially I am telling the function sorted
to order the elements of np.ndenumerate(a)
according to the key itemgetter(1)
. 基本上我告诉sorted
顺序itemgetter(1)
对np.ndenumerate(a)
的元素进行sorted
的函数。 This function itemgetter
gets the second (index 1) element from the tuples ((0, 1), 7), ((1, 1), 4),
... (ie the values) generated by np.ndenumerate(a)
. 此函数itemgetter
从np.ndenumerate(a)
生成的元组((0, 1), 7), ((1, 1), 4),
...(即值)中获取第二个(索引1)元素。
If you want numpy doing the heavy lifting, you can do something like this: 如果你想要繁重的工作,你可以做这样的事情:
>>> a = np.random.rand(100, 100)
>>> sort_idx = np.argsort(a, axis=None)
>>> np.column_stack(np.unravel_index(sort_idx[::-1], a.shape))
array([[13, 62],
[26, 77],
[81, 4],
...,
[83, 40],
[17, 34],
[54, 91]], dtype=int64)
You first get an index that sorts the whole array, and then convert that flat index into pairs of indices with np.unravel_index
. 首先得到一个索引,对整个数组进行排序,然后将该平坦索引转换为带有np.unravel_index
索引对。 The call to np.column_stack
simply joins the two arrays of coordinates into a single one, and could be replaced by the Python zip(*np.unravel_index(sort_idx[::-1], a.shape))
to get a list of tuples instead of an array. 对np.column_stack
的调用只是将两个坐标数组连接成一个坐标,并且可以用Python zip(*np.unravel_index(sort_idx[::-1], a.shape))
以得到一个列表元组而不是数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.