How to check if all values in the columns of a numpy matrix are the same?

In [45]: a
Out[45]: 
array([[1, 1, 0],
       [1, 0, 0],
       [1, 0, 0],
       [1, 1, 0]])

Compare each value to the corresponding value in the first row:

In [46]: a == a[0,:]
Out[46]: 
array([[ True,  True,  True],
       [ True, False,  True],
       [ True, False,  True],
       [ True,  True,  True]], dtype=bool)

A column shares a common value if all the values in that column are True:

In [47]: np.all(a == a[0,:], axis = 0)
Out[47]: array([ True, False,  True], dtype=bool)

The problem with np.equal.reduce can be seen by micro-analyzing what happens when it is applied to [1, 0, 0, 1]:

In [49]: np.equal.reduce([1, 0, 0, 1])
Out[50]: True

The first two items, 1 and 0 are tested for equality and the result is False:

In [51]: np.equal.reduce([False, 0, 1])
Out[51]: True

Now False and 0 are tested for equality and the result is True:

In [52]: np.equal.reduce([True, 1])
Out[52]: True

But True and 1 are equal, so the total result is True, which is not the desired outcome.

The problem is that reduce tries to accumulate the result “locally”, while we want a “global” test like np.all.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)