hamza sadiqi
hamza sadiqi

Reputation: 149

Combine elements from two arrays by pairs

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

Upvotes: 9

Views: 11716

Answers (3)

jpp
jpp

Reputation: 164643

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]])

Upvotes: 8

user3483203
user3483203

Reputation: 51175

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]]) 

Upvotes: 5

Patrick Haugh
Patrick Haugh

Reputation: 60974

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)]

Upvotes: 4

Related Questions