9

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

3 Answers 3

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]]) 
Sign up to request clarification or add additional context in comments.

3 Comments

Or just np.dstack((a, b)), though it's only a wrapper around concatenate
@BradSolomon, Thanks, think you'll also need to index [0] with that solution.
@BradSolomon column_stack is dstack without adding the additional dimension for 2 1D arrays
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]]) 

Comments

4

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

1 Comment

Note: zip + NumPy arrays are actually inefficient: see this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.