[英]Numpy check that all the element of each row of a 2D numpy array is the same
I am sure this is an already answered question, but I couldn't find anywhere.我确信这是一个已经回答的问题,但我找不到任何地方。
I want to check that all the element of each row of a 2D numpy array is the same and 0 is a possibility.我想检查 2D numpy 数组每一行的所有元素是否相同,并且有可能为 0。
For example:例如:
>>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]])
>>> a
array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
>>> function_to_find(a)
True
Looking around there are suggestions to use all()
and any()
, but I don't think it's my case.环顾四周,有使用all()
和any()
的建议,但我认为这不是我的情况。
If I use them in this way:如果我以这种方式使用它们:
>>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]])
>>> a.all()
False
>>> a.all(axis=1)
array([False, True, True, True])
>>> a.all(axis=1).any()
True
but also this give me True
and I want False
:但这也给我True
我想要False
:
>>> a = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 5]])
>>> a.all()
False
>>> a.all(axis=1)
array([False, True, True, True])
>>> a.all(axis=1).any()
True
A solution could be:一个解决方案可能是:
results_bool = np.array([])
for i in a:
results_bool = np.append(results_bool, np.all(i == i[0]))
result = np.all(results_bool)
but I would prefer to avoid loops and use numpy
.但我宁愿避免循环并使用numpy
。
Any idea?任何的想法?
You can simply do the following:您可以简单地执行以下操作:
result = (a[:, 1:] == a[:, :-1]).all()
Or, with broadcasting:或者,通过广播:
result = (a[:, 1:] == a[:, [0]]).all()
result = (a == a[:, [0]]).all()
is similar, but the above avoids the redundant comparison of the column a[:,0]
to itself. result = (a == a[:, [0]]).all()
类似,但上面避免了列a[:,0]
与其自身的冗余比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.