消除不符合匹配条件的数组行 [英] Eliminating array rows that do not meet a matching criterion
问题描述
考虑由成对的元素组成的数组M.(我用空格来强调我们将要处理元素对).实际的数组将具有大量的行和4,6,8或10列.
Consider an array, M, made up of pairs of elements. (I've used spaces to emphasize that we will be dealing with element PAIRS). The actual arrays will have a large number of rows, and 4,6,8 or 10 columns.
import numpy as np
M = np.array([[1,3, 2,1, 4,2, 3,3],
[3,5, 6,9, 5,1, 3,4],
[1,3, 2,4, 3,4, 7,2],
[4,5, 1,2, 2,1, 2,3],
[6,4, 4,1, 6,1, 4,7],
[6,7, 7,6, 9,7, 6,2],
[5,3, 1,5, 3,3, 3,3]])
问题::我想从M中删除具有该元素对与该行中任何其他对没有共同元素的行.
PROBLEM: I want to eliminate rows from M having an element pair that has no common elements with any of the other pairs in that row.
在数组M中,应删除第二行和第四行.原因如下:
第二行:该对(6,9)与(3,5),(5,1)或(3,4)没有共同的元素
第4行:对(4,5)与(1,2),(2,1)或(2,3)没有共同的元素
In array M, the 2nd row and the 4th row should be eliminated. Here's why:
2nd row: the pair (6,9) has no common element with (3,5), (5,1), or (3,4)
4th row: the pair (4,5) has no common element with (1,2), (2,1), or (2,3)
我确定有一个不错的广播解决方案,但我看不到.
I'm sure there's a nice broadcasting solution, but I can't see it.
推荐答案
这是一种广播解决方案.希望这是不言自明的:
This is a broadcasting solution. Hope it's self-explained:
a = M.reshape(M.shape[0],-1,2)
mask = ~np.eye(a.shape[1], dtype=bool)[...,None]
is_valid = (((a[...,None,:]==a[:,None,...])&mask).any(axis=(-1,-2))
|((a[...,None,:]==a[:,None,:,::-1])&mask).any(axis=(-1,-2))
).all(-1)
M[is_valid]
输出:
array([[1, 3, 2, 1, 4, 2, 3, 3],
[1, 3, 2, 4, 3, 4, 7, 2],
[6, 4, 4, 1, 6, 1, 4, 7],
[6, 7, 7, 6, 9, 7, 6, 2],
[5, 3, 1, 5, 3, 3, 3, 3]])
这篇关于消除不符合匹配条件的数组行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!