检查多维numpy数组中两个轴的相等性

时间:2018-06-18 13:12:43

标签: python arrays numpy

我给了一个三维形状(n,m,k)numpy数组。我想将其视为包含向量的二维矩阵,即具有大小为k的向量的nxm矩阵。我现在想检查两个这样的形状数组(n,m,k),第一个数组中的入口(x,y,:)等于第二个数组中的(x,y,:)。有没有一种方法可以在不使用循环的情况下在numpy中执行此操作?

我想到了以第一轴和第二轴为条件的类似A == B的东西。

1 个答案:

答案 0 :(得分:0)

a = np.arange(27).reshape(3,3,3)
b = np.zeros_like(a)
b[0,1,2] = a[0,1,2]
b[1,2,0] = a[1,2,0]
b[2,1,:] = a[2,1,:] # this is the same 3-vector, n=2, m=1

(a == b).all(axis=2) # check whether all elements of last axis are equal
# array([[False, False, False],
#        [False, False, False],
#        [False,  True, False]])