您可以通过转换数组的方式,将整个过程批量处理。让我们以一个非常类似于您问题中的示例开始:
a = np.array([[1, 1, 2, 2, 1, 3, 4], [8, 7, 7, 7, 5, 8, 8]])
现在获取索引:
_, ix = np.unique(a, return_index=True)
请注意第一个元素的索引是正确的。后续元素的偏移量取决于 a
的大小。通常情况下,偏移量为
offset = ix // a.shape[-1]
ix %= a.shape[-1]
您可以在新的
ix
中每次
offset
改变值的位置上调用
np.split
:
ix = np.split(ix, np.flatnonzero(np.diff(offset)) + 1)
所以为什么这个示例是有效的,但问题中的那个示例不是呢?关键在于
np.unique
使用基于排序的方法(使其运行时间为
O(n log n)
而不是
collections.Counter
的
O(n)
)。这意味着为了正确排序索引的顺序,每一行必须唯一且大于前一行。请注意,在你的示例中,
4
出现在两行中。你可以通过检查每行中的最大值和最小值来确保这一点:
mn = a.min(axis=1)
mx = a.max(axis=1)
diff = np.r_[0, (mx - mn + 1)[:-1].cumsum(0)] - mn
b = a + diff[:, None]
[7, 6, 6, 6, 4, 7, 7]])
请注意,您必须将累积总和偏移一个才能获得正确的索引。如果您处理大整数和/或非常大的数组,则必须更加小心地制作差分以避免溢出。
现在您可以在调用np.unique时使用b代替a。
简而言之,这是一种通用的无循环方法,适用于任何轴,而不仅仅是最后一个轴。
def global_unq(a, axis=-1):
n = a.shape[axis]
a = np.moveaxis(np.asanyarray(a), axis, -1).reshape(-1, n)
mn = a.min(-1)
mx = a.max(-1)
diff = np.r_[0, (mx - mn + 1)[:-1].cumsum(0)] - mn
_, ix = np.unique(a + diff[:, None], return_index=True)
return np.split(ix % n, np.flatnonzero(np.diff(ix // n)) + 1)