首页 > 解决方案 > 根据元素唯一性和其他条件删除 np 数组行

问题描述

考虑下面的二维整数数组:

import numpy as np

arr = np.array([[1, 3, 5, 2, 8],
                [9, 6, 1, 7, 6],
                [4, 4, 1, 8, 0],
                [2, 3, 1, 8, 5],
                [1, 2, 3, 4, 5],
                [6, 6, 7, 9, 1],
                [5, 3, 1, 8, 2]])

问题:从 arr 中消除满足两个条件的行:
a)行的元素必须是唯一的
b)从这些唯一元素行中,我想消除排列重复。

保留 arr 中的所有其他行。

在上面给出的示例中,indices 0,3,4, and 6满足条件 a) 的行。他们的元素是独一无二的。

在这 4 行中,索引为 0,3,6 的行是彼此的排列:我想保留其中的一个,比如索引 0,而 ELIMINATE 其他两个。

输出如下所示:

[[1, 3, 5, 2, 8],
 [9, 6, 1, 7, 6],
 [4, 4, 1, 8, 0],
 [1, 2, 3, 4, 5],
 [6, 6, 7, 9, 1]])

我可以通过以下方式识别满足条件 a) 的行:

s = np.sort(arr,axis=1)
arr[~(s[:,:-1] == s[:,1:]).any(1)]

但是,我完全不确定如何消除排列重复。

标签: arraysnumpy

解决方案


这是一种方法 -

# Sort along row
b = np.sort(arr,axis=1)

# Mask of rows with unique elements and select those rows
m = (b[:,:-1] != b[:,1:]).all(1)
d = b[m]

# Indices of uniq rows
idx = np.flatnonzero(m)

# Get indices of rows among them that are unique as per possible permutes
u,stidx,c = np.unique(d, axis=0, return_index=True, return_counts=True)

# Concatenate unique ones among these and non-masked ones
out = arr[np.sort(np.r_[idx[stidx], np.flatnonzero(~m)])]

或者,可以进一步优化最后一步,如下所示 -

m[idx[stidx]] = 0
out = arr[~m]

推荐阅读