numpy 在多个数组上是唯一的
numpy unique over multiple arrays
Numpy.unique 需要一维数组。如果输入不是一维数组,默认情况下会展平它。
有没有办法让它接受多个数组?为了简单起见,我们只说一对数组,我们在 2 个数组中唯一化这对元素。
例如,假设我有 2 个 numpy 数组作为输入
a = [1, 2, 3, 3]
b = [10, 20, 30, 31]
我对这两个数组都是唯一的,所以对这 4 对 (1,10)、(2,20) (3, 30) 和 (3,31)。这 4 个都是独一无二的,所以我希望我的结果是
[True, True, True, True]
如果输入如下
a = [1, 2, 3, 3]
b = [10, 20, 30, 30]
那么最后2个元素不唯一。所以输出应该是
[True, True, True, False]
您可以使用 numpy.unique()
返回的 unique_indices
值:
In [243]: def is_unique(*lsts):
...: arr = np.vstack(lsts)
...: _, ind = np.unique(arr, axis=1, return_index=True)
...: out = np.zeros(shape=arr.shape[1], dtype=bool)
...: out[ind] = True
...: return out
In [244]: a = [1, 2, 2, 3, 3]
In [245]: b = [1, 2, 2, 3, 3]
In [246]: c = [1, 2, 0, 3, 3]
In [247]: is_unique(a, b)
Out[247]: array([ True, True, False, True, False])
In [248]: is_unique(a, b, c)
Out[248]: array([ True, True, True, True, False])
您可能还会发现 有帮助。
Numpy.unique 需要一维数组。如果输入不是一维数组,默认情况下会展平它。
有没有办法让它接受多个数组?为了简单起见,我们只说一对数组,我们在 2 个数组中唯一化这对元素。
例如,假设我有 2 个 numpy 数组作为输入
a = [1, 2, 3, 3]
b = [10, 20, 30, 31]
我对这两个数组都是唯一的,所以对这 4 对 (1,10)、(2,20) (3, 30) 和 (3,31)。这 4 个都是独一无二的,所以我希望我的结果是
[True, True, True, True]
如果输入如下
a = [1, 2, 3, 3]
b = [10, 20, 30, 30]
那么最后2个元素不唯一。所以输出应该是
[True, True, True, False]
您可以使用 numpy.unique()
返回的 unique_indices
值:
In [243]: def is_unique(*lsts):
...: arr = np.vstack(lsts)
...: _, ind = np.unique(arr, axis=1, return_index=True)
...: out = np.zeros(shape=arr.shape[1], dtype=bool)
...: out[ind] = True
...: return out
In [244]: a = [1, 2, 2, 3, 3]
In [245]: b = [1, 2, 2, 3, 3]
In [246]: c = [1, 2, 0, 3, 3]
In [247]: is_unique(a, b)
Out[247]: array([ True, True, False, True, False])
In [248]: is_unique(a, b, c)
Out[248]: array([ True, True, True, True, False])
您可能还会发现