【问题标题】:Iterate over numpy array in a specific order based on values根据值以特定顺序迭代 numpy 数组
【发布时间】:2013-07-27 07:40:39
【问题描述】:

我想遍历一个 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

我希望它打印出来:

最高值的索引 下一个最高值的索引 下一个最高值的索引等

【问题讨论】:

    标签: python arrays loops numpy


    【解决方案1】:

    如果你想让 numpy 完成繁重的工作,你可以这样做:

    >>> 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)
    

    您首先获得一个对整个数组进行排序的索引,然后将该平面索引转换为具有np.unravel_index 的索引对。对 np.column_stack 的调用只是将两个坐标数组合并为一个,并且可以用 Python 替换 zip(*np.unravel_index(sort_idx[::-1], a.shape)) 以获取元组列表而不是数组。

    【讨论】:

      【解决方案2】:

      试试这个:

      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)]
      

      如果你愿意,你可以迭代这个列表。本质上,我告诉函数sorted 根据键itemgetter(1)np.ndenumerate(a) 的元素进行排序。这个函数itemgetter((0, 1), 7), ((1, 1), 4), 生成的元组((0, 1), 7), ((1, 1), 4), 中获取第二个(索引1)元素......(即值)由np.ndenumerate(a) 生成。

      【讨论】:

      • 您好 elyase 和 dkar,谢谢。我想知道你能为我解释一下吗?我对 numpy 和 python 还是很陌生。
      • 感谢 elyase,太好了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      相关资源
      最近更新 更多