sol
sol

Reputation: 1470

Fastest way to mix arrays in numpy?

a= array([1,3,5,7,9])
b= array([2,4,6,8,10])

I want to mix pair of arrays so that their sequences insert element by element Example: using a and b, it should result into

c= array([1,2,3,4,5,6,7,8,9,10])

I need to do that using pairs of long arrays (more than one hundred elements) on thousand of sequences. Any smarter ideas than pickling element by element on each array? thanks

Upvotes: 2

Views: 274

Answers (3)

Warren Weckesser
Warren Weckesser

Reputation: 114811

c = np.empty(len(a)+len(b), dtype=a.dtype)
c[::2] = a
c[1::2] = b

(That assumes a and b have the same dtype.)

You asked for the fastest, so here's a timing comparison (vstack, ravel and empty are all numpy functions):

In [40]: a = np.random.randint(0, 10, size=150)

In [41]: b = np.random.randint(0, 10, size=150)

In [42]: %timeit vstack((a,b)).T.flatten()
100000 loops, best of 3: 5.6 µs per loop

In [43]: %timeit ravel([a, b], order='F')
100000 loops, best of 3: 3.1 µs per loop

In [44]: %timeit c = empty(len(a)+len(b), dtype=a.dtype); c[::2] = a; c[1::2] = b
1000000 loops, best of 3: 1.94 µs per loop

With vstack((a,b)).T.flatten(), a and b are copied to create vstack((a,b)), and then the data is copied again by the flatten() method.

ravel([a, b], order='F') is implemented as asarray([a, b]).ravel(order), which requires copying a and b, and then copying the result to create an array with order='F'. (If you do just ravel([a, b]), it is about the same speed as my answer, because it doesn't have to copy the data again. Unfortunately, order='F' is needed to get the alternating pattern.)

So the other two methods copy the data twice. In my version, each array is copied once.

Upvotes: 9

falsetru
falsetru

Reputation: 369054

Using numpy.ravel:

>>> np.ravel([a, b], order='F')
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Upvotes: 3

mdurant
mdurant

Reputation: 28683

This'll do it:

vstack((a,b)).T.flatten()

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Upvotes: 3

Related Questions