concatenate two arrays in python with alternating the columns in numpy

Viewed 5322

How to concatenate two arrays in numpy python by taking first column from the first array and fisrt column from the second, then second column from first and second from the other, etc..? that is if I have A=[a1 a2 a3] and B=[b1 b2 b3] I want the resulting array to be [a1 b1 a2 b2 a3 b3]

3 Answers

Few approaches with stacking could be suggested -

np.vstack((A,B)).ravel('F')
np.stack((A,B)).ravel('F')
np.ravel([A,B],'F')

Sample run -

In [291]: A
Out[291]: array([3, 5, 6])

In [292]: B
Out[292]: array([13, 15, 16])

In [293]: np.vstack((A,B)).ravel('F')
Out[293]: array([ 3, 13,  5, 15,  6, 16])

In [294]: np.ravel([A,B],'F')
Out[294]: array([ 3, 13,  5, 15,  6, 16])

If we have 2d arrays then we can do the follwoing

A = np.zeros((5,2))
B = np.ones((5,2))
row_a, col_a = np.shape(A)
row_b, col_b = np.shape(B)

Mix columns in alternating fashion

assert row_a == row_b, 'number of rows should be same'
np.ravel([A,B],order="F").reshape(row_a,col_a+col_b)

This will give

array([[0., 1., 0., 1.],
       [0., 1., 0., 1.],
       [0., 1., 0., 1.],
       [0., 1., 0., 1.],
       [0., 1., 0., 1.]])

To mix rows

assert col_a == col_b, 'number of cols should be same'
np.ravel([A,B],order="F").reshape(col_a,row_a+row_b).T

Which will give

array([[0., 0.],
       [1., 1.],
       [0., 0.],
       [1., 1.],
       [0., 0.],
       [1., 1.],
       [0., 0.],
       [1., 1.],
       [0., 0.],
       [1., 1.]])

With numpy.dstack() and numpy.flatten() routines:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.dstack((a,b)).flatten()

print(result)

The output:

[1 4 2 5 3 6]
Related