1

I have an array (fe: [1,2,3,4,5,...]. I want to compare each element of the array with every other element in the array. So I want to have:

1-2
1-3
1-4
1-5
2-3
2-4
2-5
3-4
3-5
4-5

Currently, this is my code

for el_a in my_array:
    idx_a = np.where(my_array == el_a)[0][0]
    for idx_b in range(idx_a+1, len(my_array)):
        el_b = my_array[idx_b]
        print(el_a,el_b)

I compare every element el_a (first for loop), with every element el_b which comes after el_a (second for loop).

The algoritm is working correctly, however, it is very slow. Is there someone with a better, more efficient solution?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
BGR
  • 137
  • 6
  • Similar problem to a distance matrix. – Mateen Ulhaq Jul 25 '21 at 07:51
  • 1
    Does this answer your question? [Iterate over all pairwise combinations of numpy array columns](https://stackoverflow.com/questions/18155004/iterate-over-all-pairwise-combinations-of-numpy-array-columns) – Mateen Ulhaq Jul 25 '21 at 07:53

3 Answers3

2

simply use combinations from itertools.

import numpy as np
from itertools import combinations

arr = np.array([1, 2, 3, 4])
print(list(combinations(arr, 2)))

Outputs:

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
David Meu
  • 1,527
  • 9
  • 14
1

This will provide the comparison result for all possible combinations as a list:

import numpy as np
from itertools import combinations
my_array = np.array([1, 2, 3, 4, 5])
print([item[0]==item[1] for item in combinations(my_array,2)])
Pranta Palit
  • 663
  • 2
  • 5
  • 15
1

or sticking with numpy

a = np.arange(5)
b = np.arange(5)
# for both -> array([0, 1, 2, 3, 4])

(a[:, None] == b)
array([[ True, False, False, False, False],
       [False,  True, False, False, False],
       [False, False,  True, False, False],
       [False, False, False,  True, False],
       [False, False, False, False,  True]])

(a[:, None] == b).astype(np.int32)
array([[1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1]])
NaN
  • 2,212
  • 2
  • 18
  • 23