查找唯一元素并在NumPy上保留满足条件的元素

uyhoqukh  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个2D数组,每行有3个元素。
我想使用NumPy来查找行的前两个组件的唯一值。此外,对于出现一次以上的所有元素,我希望保留具有相同的第一和第二分量的所有元素中具有第三分量的最小值的元素。
我只是想出一些笨拙的想法,不知道应该如何做到这一点。

nzrxty8p

nzrxty8p1#

尝试:

# sort the array by the last column
orders = np.argsort(arr[:,-1])

# rearrange the array increasingly by last column
arr = arr[orders]

# use `unique` to find the unique pairs
# `return_index` option returns the indexes of the first occurrence for each pair
# since last column is increasing, first instance means minimum value
uniques, indexes = np.unique(arr[:,:-1], axis=0, return_index=True)

# extract the first instances together with the last column
out = arr[indexes]

示例数据:

np.random.seed(1)
arr = np.random.randint(0,2, (10,3))
arr[:,-1] = np.random.randint(0,5,10)

输出:

array([[0, 0, 1],
       [0, 1, 0],
       [1, 0, 1],
       [1, 1, 1]])

相关问题