栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

n维数组中唯一值的索引

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

n维数组中唯一值的索引

这是一种矢量化方法,适用于任意数量维的数组。此解决方案的思想是在中扩展

return_index
方法的功能
np.unique
,并返回一个数组数组,每个数组都在numpy数组中包含N个维的唯一值索引。

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

def ndix_unique(x):    """    Returns an N-dimensional array of indices    of the unique values in x    ----------    x: np.array       Array with arbitrary dimensions    Returns    -------    - 1D-array of sorted unique values    - Array of arrays. Each array contains the indices where a      given value in x is found    """    x_flat = x.ravel()    ix_flat = np.argsort(x_flat)    u, ix_u = np.unique(x_flat[ix_flat], return_index=True)    ix_ndim = np.unravel_index(ix_flat, x.shape)    ix_ndim = np.c_[ix_ndim] if x.ndim > 1 else ix_flat    return u, np.split(ix_ndim, ix_u[1:])

从问题中检查数组-

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639653.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号