For the following input:
import numpy as np
a= np.array([[0.0, 0.0, 0.0],
[1.0, 1.0, -2.234],
[0.0, 0.0, 0.0]])
b= np.array([1.0, 1.0, -2.234])
print(np.isclose(np.transpose(a), b))
Output:
$ python temp.py
--> [[False True False]
[False True False]
[False False False]]
And for following input:
print(np.isclose(a, b))
Output:
$ python temp.py
--> [[False False False]
[ True True True]
[False False False]]
I am unable to understand why np.isclose() is unable to match column element-wise but is able to do it correctly for rows. I think there is something wrong with my understanding.
My intention is to find index of matching column. To achieve this I would be further using .all(axis=) with np.where(). But before this I want to understand the behaviour of np.isclose().
CodePudding user response:
Consider your transposed array a and b:
[[ 0. 1. 0. ]
[ 0. 1. 0. ]
[ 0. -2.234 0. ]]
[ 1. 1. -2.234]
What np.isclose is doing is literally comparing (within a given tolerance) each element in each row of a with each element in b, which results in the output:
[[False True False]
[False True False]
[False False False]]
If you want to compare the arrays "column-wise", you should explicitly add an additional dimension to b. Arrays a and b would then look like this:
[[ 0. 1. 0. ]
[ 0. 1. 0. ]
[ 0. -2.234 0. ]]
[[ 1. ]
[ 1. ]
[-2.234]]
Then you can see if they are equal:
import numpy as np
a= np.array([[0.0, 0.0, 0.0],
[1.0, 1.0, -2.234],
[0.0, 0.0, 0.0]])
b = np.array([1.0, 1.0, -2.234])
a = np.transpose(a)
b = np.expand_dims(b , axis=-1)
print(np.isclose(a, b))
[[False True False]
[False True False]
[False True False]]
CodePudding user response:
a= np.array([[0.0, 0.0, 0.0],
[1.0, 1.0, -2.234],
[0.0, 0.0, 0.0]])
b= np.array([1.0, 1.0, -2.234])
print(np.isclose(np.transpose(a), b))
This resolves to
np.isclose([[0.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, -2.234, 0.0]],
[[1.0, 1.0, -2.234],
[1.0, 1.0, -2.234],
[1.0, 1.0, -2.234]])
--> [[False True False]
[False True False]
[False False False]]
And np.isclose(a, b) resolves to
np.isclose([[0.0, 0.0, 0.0],
[1.0, 1.0, -2.234],
[0.0, 0.0, 0.0]],
[[1.0, 1.0, -2.234],
[1.0, 1.0, -2.234],
[1.0, 1.0, -2.234]])
--> [[False False False]
[ True True True]
[False False False]]
You can check that b really gets broadcasted to that 2d array using np.broadcast_to(b, a.shape)
CodePudding user response:
np.isclose just checks that the values are close enough that you can consider them equal with a given threshold
By doing:
np.isclose(np.transpose(a), b)
you compare each column of a.T with each column of b.
The first column [0,0,0] is not close (i.e. almost equal) to 1. For the second column [1,1,-2.234], the first 2 values are equal to 1. For the last column [0,0,0], nothing matches -2.234.
[[False True False]
[False True False]
[False False False]]
