Skip to content Skip to sidebar Skip to footer

Interleave Rows Of Two Numpy Arrays In Python

I wanted to interleave the rows of two numpy arrays of the same size. I came up with this solution. # A and B are same-shaped arrays A = numpy.ones((4,3)) B = numpy.zeros_like(A) C

Solution 1:

It is maybe a bit clearer to do:

A = np.ones((4,3))
B = np.zeros_like(A)

C = np.empty((A.shape[0]+B.shape[0],A.shape[1]))

C[::2,:] = AC[1::2,:] = B

and it's probably a bit faster as well, I'm guessing.

Solution 2:

You can stack, transpose, and reshape:

numpy.dstack((A, B)).transpose(0, 2, 1).reshape(A.shape[0]*2, A.shape[1])

Solution 3:

I find the following approach using numpy.hstack() quite readable:

import numpy as np

a = np.ones((2,3))
b = np.zeros_like(a)

c = np.hstack([a, b]).reshape(4, 3)

print(c)

Output:

[[ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]]

It is easy to generalize this to a list of arrays of the same shape:

arrays = [a, b, c,...]

shape = (len(arrays)*a.shape[0], a.shape[1])

interleaved_array = np.hstack(arrays).reshape(shape)

It seems to be a bit slower than the accepted answer of @JoshAdel on small arrays but equally fast or faster on large arrays:

a = np.random.random((3,100))
b = np.random.random((3,100))

%%timeit
...: C = np.empty((a.shape[0]+b.shape[0],a.shape[1]))...: C[::2,:] = a...: C[1::2,:] = b...:

The slowest run took 9.29 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.3 µs per loop

%timeit c = np.hstack([a,b]).reshape(2*a.shape[0], a.shape[1])
The slowest run took 5.06 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 10.1 µs per loop

a = np.random.random((4,1000000))
b = np.random.random((4,1000000))

%%timeit
...: C = np.empty((a.shape[0]+b.shape[0],a.shape[1]))...: C[::2,:] = a...: C[1::2,:] = b...: 

10 loops, best of 3: 23.2 ms per loop

%timeit c = np.hstack([a,b]).reshape(2*a.shape[0], a.shape[1])
10 loops, best of 3: 21.3 ms per loop

Post a Comment for "Interleave Rows Of Two Numpy Arrays In Python"