查找唯一元素并将满足标准的元素保留在NumPy上

niwlg2el  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(114)

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

m0rkklqb

m0rkklqb1#

尝试:

# 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]])

相关问题