arrays - 根据元素唯一性和其他条件删除 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)]
但是,我完全不确定如何消除排列重复。
解决方案
这是一种方法 -
# 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]
推荐阅读
- python - Pycharm 没有在 py 文件中获取更新的代码
- python - 在 Pandas 数据框中获取节点祖先
- python - 使用 Waitress、Flask 和 Python 将请求记录到文件中
- javascript - jQuery按钮选择器等待ajax完成使用async-await的php exec命令不起作用
- powerbi - 使用 DAX 计算包含时间戳的日期时间间隔
- java - spring kafka 偏移增量甚至自动提交偏移设置为 false
- c# - 无效的用户名或密码 eroor 页面
- python - 为什么我的图像无法在我的 tkinter 窗口上加载?
- jenkins - Jenkins沙盒模式下Groovy对象的invokeMethod方法
- python - 打开“*.wav”时出错:文件包含未知格式的数据