加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:09:41 所属栏目:Python 来源:网络整理
导读:我有一个2D Numpy数组,包含从0到n的值. 我想得到一个长度为n的列表,这样该列表的第i个元素就是一个值为i 1的所有索引的数组(0被排除在外). 例如,输入 array([[1,1],[2,2,0]]) 我期待着 [array([[0,0],[0,2]]),array([[1,[1,1]])] 我发现了这个相关的问题: G
我有一个2D Numpy数组,包含从0到n的值.
我想得到一个长度为n的列表,这样该列表的第i个元素就是一个值为i 1的所有索引的数组(0被排除在外).

例如,输入

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

我期待着

[array([[0,0],[0,2]]),array([[1,[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]])

vals,ixs = ndix_unique(a)

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

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

让我们试试这个案例:

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

vals,ixs = ndix_unique(a)

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

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

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

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

vals,5])

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

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

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

vals,0]]),dtype=object)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读