Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 907
hamza sadiqi Avatar asked Jul 05 '18 13:07

hamza sadiqi


People also ask

How do I combine two arrays of elements?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do you combine two or more arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do you combine two elements of arrays in Java?

In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.


3 Answers

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]])
like image 53
jpp Avatar answered Oct 17 '22 09:10

jpp


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]]) 
like image 25
user3483203 Avatar answered Oct 17 '22 07:10

user3483203


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)]
like image 41
Patrick Haugh Avatar answered Oct 17 '22 09:10

Patrick Haugh