我有一个非常大的 numpy 数组,我想对它进行排序并测试它是否唯一。
我知道 numpy.unique 函数,但它会在另一次对数组进行排序以实现它。
我需要对数组进行先验排序的原因是因为 argsort 函数返回的键将用于对另一个数组重新排序。
我正在寻找一种无需再次对数组进行排序即可执行这两项操作(argsort 和唯一测试)的方法。
示例代码:
import numpy as np
import numpy.random
# generating random arrays with 2 ^ 27 columns (it can grow even bigger!)
slices = np.random.random_integers(2 ** 32, size = 2 ** 27)
values = np.random.random_integers(2 ** 32, size = 2 ** 27)
# get an array of keys to sort slices AND values
# this operation takes a long time
sorted_slices = slices.argsort()
# sort both arrays
# it would be nice to make this operation in place
slices = slices[sorted_slices]
values = values[sorted_slices]
# test 'uniqueness'
# here, the np.unique function sorts the array again
if slices.shape[0] == np.unique(slices).shape[0]:
print('it is unique!')
else:
print('not unique!')
数组 slices 和 values 都有 1 行和相同(巨大)的列数。
提前致谢。
请您参考如下方法:
您可以通过将它们的差异与 0
numpy.any(numpy.diff(slices) == 0)
请注意,numpy 将创建两个中间数组:一个具有不同值,一个具有 bool 值。
