Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix two arrays such that corresponding columns are stacked next to each other - Python

Tags:

python

numpy

Suppose I have two 2D matrix A and B, I want to concatenate each column in A with the respective column in B. For example:

A = array([[1, 1],
           [1, 1]])
B = array([[2, 3],
           [2, 3]])

So the result I expect is:

array([[1, 2, 1, 3],
       [1, 2, 1, 3]])
like image 859
victor Avatar asked Mar 10 '23 16:03

victor


1 Answers

You can try concatenate the two arrays, then rearrange the data with reshape and transpose:

x = np.concatenate((A, B)).reshape(2,2,2)
x
# array([[[1, 1],
#         [1, 1]],

#        [[2, 3],
#         [2, 3]]])

x.transpose(1,2,0).reshape(2,4)

# array([[1, 2, 1, 3],
#        [1, 2, 1, 3]])
like image 92
Psidom Avatar answered Apr 06 '23 17:04

Psidom