【问题标题】:python array sorting and indexingpython数组排序和索引
【发布时间】:2015-07-23 09:13:18
【问题描述】:

假设你有一个 3D 数组:

arr = np.zeros((9,9,9))
a[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))

如何对这个数组中所有出现的值进行排序(而不是像 np.sort 这样的轴)并显示这些值的所有索引?

输出应该是这样的:

0 at [0,0,0], [0,1,0], [0,2,1], ...etc.
1 at [5,5,5], [5,7,6], ...etc
2 at [4,5,5], ...etc
3 at ...etc

and so on

【问题讨论】:

  • 您自己尝试过什么吗?什么有效,什么无效?
  • 我尝试循环遍历所有元素,将它们的值和索引放入一个列表并按值对该列表进行排序。虽然这不是很有效(我的数据集大约有 300x300x300 数组)所以我认为它不值得一提。
  • defaultdict 效率到底够不够?
  • 不是真的,我会用 np.unravel_index 试试 Eelco 的方法,看看能不能绕过分组……

标签: python arrays sorting numpy


【解决方案1】:

获取分组值的一个非常简单的方法是defaultdict

from collections import defaultdict

grouped = defaultdict(list)
for position, v in np.ndenumerate(arr):
    grouped[v].append(position)

for v, positions in grouped.items():
    print('{0} is at {1}'.format(v, positions))

【讨论】:

    【解决方案2】:
    import numpy as np
    arr = np.zeros((9,9,9))
    arr[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))
    
    S = np.sort(arr,axis=None)
    I = np.argsort(arr, axis=None)
    print np.array([S] + list( np.unravel_index(I, arr.shape))).T
    

    这应该或多或少地为您提供您正在寻找的结果;这里的精髓在于 unravel_index。如果您坚持以按数组值分组的方式获取结果,您可以搜索stackoverflow以在numpy中进行分组。

    【讨论】:

      【解决方案3】:

      这会起作用(虽然效率不是很高):

      arr = np.zeros((9,9,9))
      arr[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))
      
      arr = arr.flatten () # Flatten the array, arr is now a (9 * 9 * 9) vector
      arr.sort ()          # Sort the now 1-d array
      arr.reshape ((9, 9, 9)) # Reshape it
      
      for i in range(0, 5):
          id = np.array(np.where (arr == i)).T
          print('{} at {}'.format(i, ', '.join(map(str, c))))
      

      【讨论】:

        猜你喜欢
        • 2016-06-03
        • 2012-12-20
        • 2015-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多