Alex Rivera | Logout

Interleaving two NumPy arrays efficiently

Asked 2011-03-18T01:20:51.057
121

Assume the following arrays are given:

a = array([1, 3, 5])
b = array([2, 4, 6])

How would one interleave them efficiently so that one gets a third array like the following?

c = array([1, 2, 3, 4, 5, 6])

It can be assumed that length(a) == length(b).

Edit
Report

2 Answers

4

Maybe this is more readable than JoshAdel's solution:

c = numpy.vstack((a,b)).ravel([-1])
answered 2011-03-18T15:12:22.973
2

vstack sure is an option, but a more straightforward solution for your case could be the hstack:

a = array([1,3,5])
b = array([2,4,6])
hstack((a,b)) # Remember it is a tuple of arrays that this function swallows in.
array([1, 3, 5, 2, 4, 6])
sort(hstack((a,b)))
array([1, 2, 3, 4, 5, 6])

And more importantly this works for arbitrary shapes of a and b.

Also you may want to try out dstack:

a = array([1,3,5])
b = array([2,4,6])
dstack((a,b)).flatten()
array([1, 2, 3, 4, 5, 6])

You’ve got options now!

answered 2011-03-19T04:33:31.120

Your Answer