在Python中将数组与精确值和近似值进行比较
我有一个Python矩阵数组,例如:在Python中将数组与精确值和近似值进行比较,python,numpy,Python,Numpy,我有一个Python矩阵数组,例如: a = array([[0, 2, 1, 1.4142, 4, 7], [3, 0, 1.4142, 9, 2, 0], [1.4142, 0, 0, 1, 1, 3]]) 我想将这个数组的所有元素都转换为1,或者将不同于sqrt(2)(1.4142)的元素转换为0。即: a = array([[0, 0, 1, 1.4142, 0, 0], [0, 0, 1.4142, 0, 0, 0],
a = array([[0, 2, 1, 1.4142, 4, 7],
[3, 0, 1.4142, 9, 2, 0],
[1.4142, 0, 0, 1, 1, 3]])
我想将这个数组的所有元素都转换为1,或者将不同于sqrt(2)(1.4142)的元素转换为0。即:
a = array([[0, 0, 1, 1.4142, 0, 0],
[0, 0, 1.4142, 0, 0, 0],
[1.4142, 0, 0, 1, 1, 0]])
我试过这个
a[(a != 1).any() or not (np.isclose(a, np.sqrt(2))).any()] = 0
和一些变化,但我不能让它工作。Thx.只需使用掩蔽-
m1 = np.isclose(a,1) # use a==1 for exact matches
m2 = np.isclose(a,np.sqrt(2))
a[~(m1 | m2)] = 0
只需使用掩蔽-
m1 = np.isclose(a,1) # use a==1 for exact matches
m2 = np.isclose(a,np.sqrt(2))
a[~(m1 | m2)] = 0
你可以试试:
np.where((a == 1.4142), a, a == 1)
你可以试试:
np.where((a == 1.4142), a, a == 1)
为什么不检查两个数组元素的和和和积?如果我错了,请更正。这应该适用于正数。为什么不检查两个数组的元素总和和乘积?正确如果我错了,这应该适用于正数