如何检查numpy矩阵的列中的所有值是否相同

如何检查numpy矩阵的列中的所有值是否相同

本文介绍了如何检查numpy矩阵的列中的所有值是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查numpy数组/矩阵的列中的所有值是否相同.我尝试使用 ufunc equalreduce,但是似乎并非在所有情况下都有效:

I want to check if all values in the columns of a numpy array/matrix are the same.I tried to use reduce of the ufunc equal, but it doesn't seem to work in all cases:

In [55]: a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]])

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

In [57]: np.equal.reduce(a)
Out[57]: array([ True, False,  True], dtype=bool)

In [58]: a = np.array([[1,1,0],[1,0,0],[1,0,0],[1,1,0]])

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

In [60]: np.equal.reduce(a)
Out[60]: array([ True,  True,  True], dtype=bool)

为什么第二种情况下的中间列也计算为True,而应该为False?

Why does the middle column in the second case also evaluate to True, while it should be False?

感谢您的帮助!

推荐答案

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)

如果该列中的所有值均为True,则该列共享一个公共值:

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)


np.equal.reduce的问题可以通过微观分析应用于[1, 0, 0, 1]时发生的情况来看出:


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

对前两个项目10进行相等性测试,结果为False:

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

现在对False0进行相等性测试,结果为True:

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

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

但是True和1相等,所以总结果为True,这不是期望的结果.

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

问题是reduce试图本地"累积结果,而我们希望像np.all这样的全局"测试.

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

这篇关于如何检查numpy矩阵的列中的所有值是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:48