python – ndarray中唯一值的N维索引

我有一个2D Numpy数组,包含从0到n的值.

我想得到一个长度为n的列表,这样该列表的第i个元素就是一个值为i 1的所有索引的数组(0被排除在外).

例如,输入

array([[1, 0, 1],
   [2, 2, 0]])

我期待着

[array([[0, 0], [0, 2]]), array([[1,0], [1,1]])]

我发现了这个相关的问题:
Get a list of all indices of repeated elements in a numpy array
这可能会有所帮助,但我希望找到一个更直接的解决方案,不需要对数组进行扁平化和排序,并且尽可能高效.

最佳答案 这是一个矢量化方法,适用于任意数量维度的数组.此解决方案的想法是在
np.unique中扩展return_index方法的功能,并返回一个数组数组,每个数组包含n维索引,其中给定numpy数组中的唯一值出现.

对于更紧凑的解决方案,我在不同的步骤中定义了以下功能以及一些解释.

 一般解决方案

def ndix_unique(x):
    """
    Finds the indices where each unique
    value in x is found
    ----------
    x: np.array
       Can have multiple dimensions
    Returns
    -------
    - 1darray of sorted unique values
    - Array of arrays. Each array contains the indices where a
      given value in x is found, where the values are sorted
    """
    # flattens x. Both will be necessary
    x_ = x.ravel()
    # Sort y using np.argsort
    ix_ = np.argsort(x_)
    # Finds the indices in x_ that result in the
    # unique array. Used later on to split
    u, s = np.unique(x_[ix_], return_index=True)
    # Mapping of the 1D indices to n-dimensional
    # indices taking the shape of x as a reference
    ix_ndim = np.unravel_index(ix_, x.shape)
    # Stack these as columns 
    ix = np.column_stack(ix_ndim) if x.ndim > 1 else ix_
    # Split the nD coordinates using the indices in s
    # i.e. where the changes of values take place
    return u, np.split(ix, s[1:])

 例子

让我们首先使用建议的ndarray检查结果:

a = np.array([[1, 0, 1],[2, 2, 0]])

vals, ixs = ndix_unique(a)

print(vals)
array([0, 1, 2])

print(ixs)
[array([[0, 1],
        [1, 2]]), 
 array([[0, 0],
        [0, 2]]), 
 array([[1, 0],
        [1, 1]])]

让我们试试这个案例:

a = np.array([[1,1,4],[2,2,1],[3,3,1]])

vals, ixs = ndix_unique(a)

print(vals)
array([1, 2, 3, 4])

print(ixs)
array([array([[0, 0],
              [0, 1],
              [1, 2],
              [2, 2]]),
       array([[1, 0],
              [1, 1]]), 
       array([[2, 0],
              [2, 1]]),
       array([[0, 2]])], dtype=object)

现在让我们尝试一维数组:

a = np.array([1,5,4,3,3])

vals, ixs = ndix_unique(a)

print(vals)
array([1, 3, 4, 5])

print(ixs)
array([array([0]), array([3, 4]), array([2]), array([1])], dtype=object)

最后是3D ndarray的另一个例子:

a = np.array([[[1,1,2]],[[2,3,4]]])

vals, ixs = ndix_unique(a)

print(vals)
array([1, 2, 3, 4])

print(ixs)
array([array([[0, 0, 0],
              [0, 0, 1]]),
       array([[0, 0, 2],
              [1, 0, 0]]), 
       array([[1, 0, 1]]),
       array([[1, 0, 2]])], dtype=object)
点赞