pythonarraysnumpy

Interleaving two NumPy arrays efficiently


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


Solution

  • I like Josh's answer. I just wanted to add a more mundane, usual, and slightly more verbose solution. I don't know which is more efficient. I expect they will have similar performance.

    import numpy as np
    
    a = np.array([1,3,5])
    b = np.array([2,4,6])
    
    c = np.empty((a.size + b.size,), dtype=a.dtype)
    c[0::2] = a
    c[1::2] = b