I have two arrays A and B
JavaScript
x
3
1
A = np.array([[9, 10, 11, 12.0],[13 14 15 16.3]])
2
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])
3
I want to compare a couple of the elements of A[:,2:4] with couple elements of B[:,2:4] and print out the rows where they are equal or approximate? Here is my approach just for only A[:,3]
JavaScript
1
9
1
import math
2
import cmath
3
import numpy as np
4
A = np.array([[9, 10, 11, 12],[13, 14, 15, 16.3]])
5
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])
6
for k in range(0,A.shape[0]):
7
i = np.where(np.isclose(B[:,3], A[k,3], atol=0.5))
8
print (i)
9
How can I do it with both A[:,2] and A[:,3] ?
Many thanks
Advertisement
Answer
I think you are looking for something like this:
JavaScript
1
9
1
import numpy as np
2
3
indexes_to_compare = range(2,4)
4
A = np.array([[9, 10, 11, 12],[13, 14, 15, 16.3]])
5
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])
6
7
for a in A:
8
print(np.where(np.all(np.isclose(B[:,indexes_to_compare], a[indexes_to_compare], atol=0.5), axis=1))[0])
9
You compare B
with each row of A
, taking into consideration only few indexes.
Thus you:
- Check if
B
is close to a row ofA
(in selected indexes) withnp.isclose(_)
- Keep only rows where all selected indexes are close, with
np.all(_, axis=1)
- Get index of such rows with
np.where
If you want to make sure to only output one row of B
per cycle, just use np.where(_)[0][0]