6

I am looking for a fast method to merge two numpy arrays in python in the following fashion. For example, if I have the following two arrays,

arr1 = np.array([0.0, 1.0, 11.0, 111.0])
arr2 = np.array([0.5, 1.5, 11.5, 111.5])

then I would want the merged array (say arr3) to contain elements of arr1 and arr2 in alternating indices. Like,

arr3 = np.array([0.0, 0.5, 1.0, 1.5, 11.0, 11.5, 111.0, 111.5]) 

I realize that I can achieve this using two for loops, where I can store elements of arr1 and arr2 into alternate indices (of arr3). But, in my actual work, I will be dealing with huge arrays (arr1 and arr2), and I want to make sure that I am using an efficient and fast approach to achieve this functionality (i.e. creation of arr3)

I will very much appreciate any help.

Commoner
  • 1,678
  • 3
  • 19
  • 34

2 Answers2

8

This is one way. Append or stack-based methods are inefficient, as memory is not pre-allocated. Manipulation of numpy arrays works best when memory allocation is determined ahead of time.

arr1 = np.array([0.0, 1.0, 11.0, 111.0])
arr2 = np.array([0.5, 1.5, 11.5, 111.5])

arr3 = np.zeros(arr1.shape[0] + arr2.shape[0], dtype=arr1.dtype)
arr3[::2] = arr1
arr3[1::2] = arr2

print(arr3)

[   0.     0.5    1.     1.5   11.    11.5  111.   111.5]
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Roughly 3 times faster than the dstack + flatten solution with 1000-element arrays on my machine, cheers! – Aubergine Oct 28 '20 at 01:39
4

Here is another way:

In []:
np.dstack((arr1, arr2)).flatten()

Out[]:
array([  0. ,   0.5,   1. ,   1.5,  11. ,  11.5, 111. , 111.5])
AChampion
  • 29,683
  • 4
  • 59
  • 75