8

Is there an easy way in Numpy to generate an array of number pairs from 2 1D numpy arrays (vectors) without looping?

input:

a = [1, 2, 3]
b = [4, 5, 6]

output:

c = [(1,4), (1,5), (1,6), (2,4), (3,5), (2,6), (3,4), (3,5), (3,6)]

I wondering if there is a function that does something similar to this:

c = []
for i in range(len(a)):
    for j in range(len(b)):
        c.append((a[i], b[j]))
marillion
  • 10,618
  • 19
  • 48
  • 63

1 Answers1

13

You can use itertools.product for this:

from itertools import product

c = list(product(a, b))

This gives:

c == [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    I will accept this answer, since it is valid, however I got away with it using a simple list comprehension: `c = [(i, j) for i in a for j in b]` – marillion Feb 11 '14 at 20:17
  • 1
    How do you refer to each coordinate of an element in c? – Bran Jul 24 '16 at 15:07
  • 5
    For anyone in the future you can do something such as: `ordered_pairs = np.column_stack((a, b))`...returns `[[1 4][2 5][3 6]]` for ops question. @Subzero-273K - to answer you, you can access ordered each element in the ordered pair using: `ordered_pairs[0, 0]` which will result in 1 being returned. If you'd like to select the second number in each element you can use `[:, 1]` – anshanno Nov 06 '16 at 21:02
  • 3
    I'd love to see a solution that stays within numpy to avoid the overhead of Python loops. Broadcasting, fancy indexing, vectorizing, etc. – Andrew Sep 14 '18 at 04:36
  • i have a slightly diff problem but this solution can help. i want to generate all pairs out of a single array. Eg. x=[1, 2, 3] will give [1, 2], [1, 3], [2, 3] and i could use product(x, x). Is there an option to suppress the "self" such as [1, 1]? – kawingkelvin Feb 27 '20 at 19:16