8

So I want to concatenate two arrays but by pairs. The input is as follows:

a = array([1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
b = array([0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0])

And the output should be as follows:

out_put = 
[[1, 0],
[1, 0],
[0, 1],
[1, 0],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[1, 0]]

I managed to get such result by iterating over the two arrays

out_put = [[a[i],b[i]] for i in range(len(a)]

but I wonder if there any faster way .

Thank you

jpp
  • 159,742
  • 34
  • 281
  • 339
hamza sadiqi
  • 139
  • 2
  • 10

3 Answers3

8

For a vectorised solution, you can stack and transpose:

a = np.array([1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
b = np.array([0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0])

c = np.vstack((a, b)).T
# or, c = np.dstack((a, b))[0]

array([[1, 0],
       [1, 0],
       [0, 1],
       [1, 0],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [0, 1],
       [1, 0]])
jpp
  • 159,742
  • 34
  • 281
  • 339
5

Using np.column_stack

Stack 1-D arrays as columns into a 2-D array.

np.column_stack((a, b))

array([[1, 0],  
       [1, 0],  
       [0, 1],  
       [1, 0],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [0, 1],  
       [1, 0]]) 
user3483203
  • 50,081
  • 9
  • 65
  • 94
3

You can use the zip function to combine any two iterables like this. It will continue until it reaches the end of the shorter iterable

list(zip(a, b))
# [(1, 0), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0)]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • Note: `zip` + NumPy arrays are actually inefficient: see [this answer](https://stackoverflow.com/a/50399219/9209546). – jpp Jul 05 '18 at 13:23