[英]How to check if all values of an array are equal to each other?
I want to check if an array has all the same value in it.我想检查一个数组中是否有相同的值。 An example would be as follows.一个例子如下。
array1 = np.array([1,1,1,1,1]) would return True
array2 = np.array([1,0,1,0,1]) would return False
I know how to check if all values in an array are equal to a certain value.我知道如何检查数组中的所有值是否都等于某个值。 But I want to check if all values in the array are equal to each other, no matter what the value is.但是我想检查数组中的所有值是否彼此相等,无论值是什么。 Is there a way to do this with just Numpy without creating a function?有没有办法在不创建函数的情况下只用 Numpy 来做到这一点?
You can use python sets.您可以使用 python 集。 If the length of the set is 1, all values are the same:如果集合的长度为 1,则所有值都相同:
>>> len(set(array1)) == 1
True
>>> len(set(array2)) == 1
False
This works too and seems to be slightly faster than some other approaches:这也有效,并且似乎比其他一些方法略快:
>>> array1 = np.array([1,1,1,1,1])
>>> array2 = np.array([1,0,1,0,1])
>>> (array1 == array1[0]).all()
True
>>> (array2 == array2[0]).all()
False
Some very coarse timing figures for a 10k array, compared to other solutions:与其他解决方案相比,10k 阵列的一些非常粗略的时序图:
np.isin()
: 1.23 msec np.isin()
:1.23 毫秒set()
: 2.63 msec set()
:2.63 毫秒This can be used- np.unique这可以使用- np.unique
import numpy as np
array1 = np.array([1,1,1,1,1])
#following passes assertion test
assert(len(np.unique(array1, return_counts=True)[0])==1)
#without getting counts of unique values
#assert(len(np.unique(array1))==1)
array2 = np.array([1,0,1,0,1])
#following will throw an assertion error
assert(len(np.unique(array2, return_counts=True)[0])==1)
My attempt would be to compare all items to the first item and then check if the result contains a False
:我的尝试是将所有项目与第一个项目进行比较,然后检查结果是否包含False
:
import numpy as np
array1 = np.array([1,1,1,1,1])
print(not np.isin(False, array1 == array1[0]))
You can try to use all() :您可以尝试使用all() :
For example:例如:
all(array1)
> True
all(array2)
> False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.