How do I combine two numpy arrays element wise in python? How do I combine two numpy arrays element wise in python? arrays arrays

How do I combine two numpy arrays element wise in python?


Use np.insert:

>>> A = np.array([1, 3, 5, 7])>>> B = np.array([2, 4, 6, 8])>>> np.insert(B, np.arange(len(A)), A)array([1, 2, 3, 4, 5, 6, 7, 8])


You can also use slices :

C = np.empty((A.shape[0]*2), dtype=A.dtype)C[0::2] = AC[1::2] = B


Some answers suggested sorting, but since you want to combine them element-wise sorting won't achieve the same result.

Here is one way to do it

C = []for elem in zip(A, B):    C.extend(elem)