Interweaving Two Numpy Arrays

Interweaving two numpy arrays

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

Interleave rows of two numpy arrays in Python

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,:] = A
C[1::2,:] = B

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

How to interleave numpy.ndarrays?

Stack those along the third axis with np.dstack and reshape back to 2D -

np.dstack((a,b)).reshape(a.shape[0],-1)

With three arrays or even more number of arrays, simply add in those. Thus, for three arrays, use : np.dstack((a,b,c)) and reshape with c being the third array.

Sample run -

In [99]: a
Out[99]:
array([[8, 4, 0, 5, 6],
[0, 2, 3, 0, 6],
[4, 4, 0, 6, 5],
[7, 5, 0, 7, 0],
[6, 7, 4, 7, 2]])

In [100]: b
Out[100]:
array([[3, 5, 8, 6, 5],
[5, 6, 8, 8, 4],
[8, 3, 3, 3, 5],
[2, 1, 1, 1, 3],
[5, 7, 7, 5, 7]])

In [101]: np.dstack((a,b)).reshape(a.shape[0],-1)
Out[101]:
array([[8, 3, 4, 5, 0, 8, 5, 6, 6, 5],
[0, 5, 2, 6, 3, 8, 0, 8, 6, 4],
[4, 8, 4, 3, 0, 3, 6, 3, 5, 5],
[7, 2, 5, 1, 0, 1, 7, 1, 0, 3],
[6, 5, 7, 7, 4, 7, 7, 5, 2, 7]])

Interleave numpy arrays

You can try to use np.insert

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]])
np.insert(y, obj=(0, 1, 2), values=x, axis=0)

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

(0, 1, 2) refers to the indexes in y that you would like to insert into before insertion.

EDIT : One can use obj=range(y.shape[0]) for arbitrary length of y. Thanks for Chiel's suggestion.

Please see the tutorial for more information.

Numpy concatenate arrays with interleaving

Use np.dstack or np.stack to stack along the last axis that gives us a 3D array and then reshape back to 2D -

np.dstack([a,b,c,d]).reshape(a.shape[0],-1)
np.stack([a,b,c,d],axis=2).reshape(a.shape[0],-1)

Interleaving NumPy arrays with mismatching shapes

Here's a mostly NumPy based approach using also zip_longest to interleave the arrays with a fill value:

def interleave(*a):
# zip_longest filling values with as many NaNs as
# values in second axis
l = *zip_longest(*a, fillvalue=[np.nan]*a[0].shape[1]),
# build a 2d array from the list
out = np.concatenate(l)
# return non-NaN values
return out[~np.isnan(out[:,0])]

a1 = np.array([[11,12], [41,42]])
a2 = np.array([[21,22], [51,52], [71,72], [91,92], [101,102]])
a3 = np.array([[31,32], [61,62], [81,82]])

interleave(a1,a2,a3)

array([[ 11., 12.],
[ 21., 22.],
[ 31., 32.],
[ 41., 42.],
[ 51., 52.],
[ 61., 62.],
[ 71., 72.],
[ 81., 82.],
[ 91., 92.],
[101., 102.]])

How to de-interleave array in numpy?

Permute axes and reshape with the idea being borrowed off General idea for nd to nd transformation. -

N = 4 # number of rows to split with
n = a.shape[1]
a.reshape(-1,N,n).swapaxes(1,2).reshape(-1,n*N)

Merging two numpy arrays with sequential rows

You can create an output array and place the inputs into it by index. The output is always

output = np.empty((x.shape[0] + y.shape[0], x.shape[1]), dtype=x.dtype)

You can generate the output indices like:

idx = (np.arange(0, output.shape[0] - n + 1, m + n)[:, None] + np.arange(n)).ravel()
idy = (np.arange(n, output.shape[0] - m + 1, m + n)[:, None] + np.arange(m)).ravel()

This creates a column vector of start indices and adds the n or m steps to mark all rows where the inputs go. You can then assign the inputs directly:

output[idx, :] = x
output[idy, :] = y

Creation of numpy array from two arrays, such that alternate indices contain elements from different arrays

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]

Interleaving last axis of n-d numpy arrays

You can stack the two arrays along a new axis first (i.e. the 4th axis here), and then flatten the last two dimensions which will interleave elements on the 3rd axis from the original arrays:

np.stack((a, b), axis=-1).reshape(a.shape[:-1] + (-1,))

#[[[4 8 7 3 1 2]
# [3 1 8 7 1 9]
# [0 0 3 0 7 6]
# [1 1 5 0 5 1]
# [1 6 7 0 6 2]]
# ...


Related Topics



Leave a reply



Submit