和Bitwise的回答很相似:
def fn(a):
return lambda b: np.all(a==b, axis=1)
matches = np.apply_along_axis(fn(M), 1, L[:,:2])
result = L[np.any(matches, axis=1)]
幕后发生的事情是这样的(我将使用 Bitwise 的示例,它更容易演示):
>>> M
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11]])
>>> M.shape+=(1,)
>>> M
array([[[ 0],
[ 1]],
[[ 2],
[ 3]],
[[ 4],
[ 5]],
[[ 6],
[ 7]],
[[ 8],
[ 9]],
[[10],
[11]]])
这里我们为 M 数组添加了另一个维度,现在是 (6,2,1)。
>>> L2 = L[:,:-1].T
然后我们去掉最后一列2,对数组进行转置,使得维度为(2,4)
神奇的是,M 和 L2 现在可以广播到维度为 (6,2,4) 的数组。
正如 numpy 的文档所述:
一组数组被称为“可广播”到相同的形状,如果
上述规则产生一个有效的结果,即以下之一是
真的:
The arrays all have exactly the same shape.
The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1.
The arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2.
例子
如果a.shape是(5,1),b.shape是(1,6),c.shape是(6,),d.shape是
() 使得 d 是一个标量,那么 a、b、c 和 d 都可以广播到
尺寸(5,6);和
a acts like a (5,6) array where a[:,0] is broadcast to the other columns,
b acts like a (5,6) array where b[0,:] is broadcast to the other rows,
c acts like a (1,6) array and therefore like a (5,6) array where c[:] is broadcast to every row, and finally,
d acts like a (5,6) array where the single value is repeated.
M[:,:,0] 将重复 4 次以填充 3 个暗淡,L2 将添加一个新维度并重复 6 次以填充它。
>>> B = np.broadcast_arrays(L2,M)
>>> B
[array([[[ 0, 3, 6, 9],
[ 1, 4, 7, 10]],
[[ 0, 3, 6, 9],
[ 1, 4, 7, 10]],
[[ 0, 3, 6, 9],
[ 1, 4, 7, 10]],
[[ 0, 3, 6, 9],
[ 1, 4, 7, 10]],
[[ 0, 3, 6, 9],
[ 1, 4, 7, 10]],
[[ 0, 3, 6, 9],
[ 1, 4, 7, 10]]]),
array([[[ 0, 0, 0, 0],
[ 1, 1, 1, 1]],
[[ 2, 2, 2, 2],
[ 3, 3, 3, 3]],
[[ 4, 4, 4, 4],
[ 5, 5, 5, 5]],
[[ 6, 6, 6, 6],
[ 7, 7, 7, 7]],
[[ 8, 8, 8, 8],
[ 9, 9, 9, 9]],
[[10, 10, 10, 10],
[11, 11, 11, 11]]])]
我们现在可以逐元素比较它们:
>>> np.equal(*B)
array([[[ True, False, False, False],
[ True, False, False, False]],
[[False, False, False, False],
[False, False, False, False]],
[[False, False, False, False],
[False, False, False, False]],
[[False, False, True, False],
[False, False, True, False]],
[[False, False, False, False],
[False, False, False, False]],
[[False, False, False, False],
[False, False, False, False]]], dtype=bool)
行到行(轴 = 1):
>>> np.all(np.equal(*B), axis=1)
array([[ True, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, True, False],
[False, False, False, False],
[False, False, False, False]], dtype=bool)
在 L 上聚合:
>>> C = np.any(np.all(np.equal(*B), axis=1), axis=0)
>>> C
array([ True, False, True, False], dtype=bool)
这为您提供了应用于 L 的布尔掩码。
>>> L[C]
array([[0, 1, 2],
[6, 7, 8]])
apply_along_axis 将利用相同的功能,但减少 L 的维度而不是增加 M 的维度(从而添加隐式循环)。