这是一种矢量化方法,适用于任意数量维的数组。此解决方案的思想是在中扩展
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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)