Concatenate two arrays as coordinate-couples

Viewed 930

I have two numpy arrays that I need to combine in a two dimensional array: each row has to be a coordinates couple. For example, if the numpy arrays were:

[1 2 3]
[a b c]

then what I'm aiming for is:

[[1 a]
 [1 b]
 [1 c]
 [2 a]
 [2 b]
 [2 c]
 [3 a]
 [3 b]
 [3 c]]

I've tried this:

    import numpy as np

    x1_start, x1_stop, x1_step = 88.5, 91.5, 0.2
    x2_start, x2_stop, x2_step = 82, 90, 0.5

    x1 = np.arange(x1_start, x1_stop, x1_step)
    x2 = np.arange(x2_start, x2_stop, x2_step)

    x1x2 = np.array([])

    for k in range(len(x1)):
        for h in range(len(x2)):
            list = [x1[k], x2[h]]
            np.append(x1x2, list ,0)

but the result is an empty numpy array. Alternatively, I've tried this:

x1x2 = []

for k in range(len(x1)):
    for h in range(len(x2)):
        x1x2.append([x1[k],x2[h]])

print(type(x1x2))
np.asarray(x1x2)
print(type(x1x2))

the list contains the correct numbers, but when i print its type it turns out to be a list either before and after the np.array cast.

1 Answers

One way with meshgrid

x = np.array([1,2,3])
y = np.array([4,5,6])
np.array(np.meshgrid(x, y)).T.reshape(-1, 2)

will result in

array([[1, 4],
       [1, 5],
       [1, 6],
       [2, 4],
       [2, 5],
       [2, 6],
       [3, 4],
       [3, 5],
       [3, 6]])

meshgrid pairs all possible combinations, transpose to put them together, then the reshape to what is needed.

Related