How to stack every n rows of two numpy arrays

Viewed 148

I have 2 numpy arrays and I would like to stack them like this:

    arr1 = [[1,2,3]
            [4,5,6]
            [7,8,9]
            [10,11,12]]
    arr2 = [[a,b,c]
            [d,e,f]
            [g,h,i]
            [j,k,l]]

    SomeStackFunction(a,b) # need this funtion

    output_array = [[1,2,3]
                    [4,5,6]
                    [a,b,c]
                    [d,e,f]
                    [7,8,9]
                    [10,11,12]
                    [g,h,i]
                    [j,k,l]]

What's the most efficient way to do this? I have fairly large arrays and actually want to stack the every 4 rows.

4 Answers

If for some reason you don't want to use numpy:

arr1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
arr2 = [['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']]

output_array = []
ind1 = 0
ind2 = 0

for i in range(len(arr1)):

    if i % 2 == 0:
        output_array.append(arr1[ind1])
        ind1 += 1
        output_array.append(arr1[ind1])
        ind1 += 1
    else:
        output_array.append(arr2[ind2])
        ind2 += 1
        output_array.append(arr2[ind2])
        ind2 += 1

Output:

[[1, 2, 3],[4, 5, 6],['a', 'b', 'c'],['d', 'e', 'f'],[7, 8, 9],[10, 11, 12],['g', 'h', 'i'],['j', 'k', 'l']]

If you can use numpy I have a funny one for you:

arr1 = np.asarray([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
arr2 = np.asarray([[0,10,20],[30,40,50],[60,70,80],[90,100,110]])

tmp_arr1  = arr1.reshape((arr1.shape[0]//2, -1))
tmp_arr2 = arr2.reshape((arr2.shape[0]//2, -1))

out = np.stack((tmp_arr1, tmp_arr2), axis=1).reshape((2*arr1.shape[0],arr1.shape[1]))

Output:

>>> print(out)
[[  0   1   2]
 [  3   4   5]
 [  0  10  20]
 [ 30  40  50]
 [  6   7   8]
 [  9  10  11]
 [ 60  70  80]
 [ 90 100 110]]

This method may seem rather confusing, but using only numpy functions provides very good performance. It might be a little overkill for your problem but it's good to know that it can be done with a little ingenuity.

If you have numpy arrays, you can use the numpy stack function as descibred in Numpy.org Docs

Example from the docs:

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.stack((a, b))
--> array([[1, 2, 3],
           [2, 3, 4]])

You can try this:

arr1 = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [10, 11, 12]]

arr2 = [['a', 'b', 'c'],
        ['d', 'e', 'f'],
        ['g', 'h', 'i'],
        ['j', 'k', 'l']]

[e for tup in list(zip(arr1[::2], arr1[1::2], arr2[::2], arr2[1::2])) for e in tup]

# Out[67]: 
# [[1, 2, 3],
#  [4, 5, 6],
#  ['a', 'b', 'c'],
#  ['d', 'e', 'f'],
#  [7, 8, 9],
#  [10, 11, 12],
#  ['g', 'h', 'i'],
#  ['j', 'k', 'l']]
Related