Skip to content
Advertisement

Compare two arrays and print out Index of row in python

I have two arrays A and B

A = np.array([[9, 10, 11, 12.0],[13 14 15 16.3]])
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])

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]

import math
import cmath
import numpy as np
A = np.array([[9, 10, 11, 12],[13, 14, 15, 16.3]])
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])
for k in range(0,A.shape[0]):
    i = np.where(np.isclose(B[:,3], A[k,3], atol=0.5))
    print (i)

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:

import numpy as np

indexes_to_compare = range(2,4)
A = np.array([[9, 10, 11, 12],[13, 14, 15, 16.3]])
B = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16],[17, 18, 19, 20]])

for a in A:
    print(np.where(np.all(np.isclose(B[:,indexes_to_compare], a[indexes_to_compare], atol=0.5), axis=1))[0])

You compare B with each row of A, taking into consideration only few indexes.

Thus you:

  • Check if B is close to a row of A (in selected indexes) with np.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]

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement