pramesh
pramesh

Reputation: 1954

Compare numpy arrays of different shapes

I have two numpy arrays of shapes (4,4) and (9,4)

matrix1 = array([[ 72.        ,  72.        ,  72.        ,  72.        ],
       [ 72.00396729,  72.00396729,  72.00396729,  72.00396729],
       [596.29998779, 596.29998779, 596.29998779, 596.29998779],
       [708.83398438, 708.83398438, 708.83398438, 708.83398438]])

matrix2 = array([[ 72.02400208,  77.68997192, 115.6057663 , 105.64997101],
       [120.98195648,  77.68997192, 247.19802856, 105.64997101],
       [252.6330719 ,  77.68997192, 337.25634766, 105.64997101],
       [342.63256836,  77.68997192, 365.60125732, 105.64997101],
       [ 72.02400208, 113.53997803, 189.65515137, 149.53997803],
       [196.87202454, 113.53997803, 308.13119507, 149.53997803],
       [315.3480835 , 113.53997803, 405.77023315, 149.53997803],
       [412.86999512, 113.53997803, 482.0453186 , 149.53997803],
       [ 72.02400208, 155.81002808, 108.98254395, 183.77003479]])

I need to compare all the rows of matrix2 with every row of matrix1. How can this be done without looping in the elements of matrix1?

Upvotes: 3

Views: 685

Answers (1)

amzon-ex
amzon-ex

Reputation: 1744

If it is about element-wise comparison of the rows, then check this example:

# Generate sample arrays
a = np.random.randint(0, 5, size = (4, 3))
b = np.random.randint(-1, 6, size = (5, 3))

# Compare
a == b[:, None]

The last line does the comparison for you. The output array will have shape (num_of_b_rows, num_of_a_rows, common_num_of_cols): in this case, (5, 4, 3).

Upvotes: 4

Related Questions