Reputation: 149
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
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
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
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