Mix two arrays so that the corresponding columns are next to each other - Python

Suppose I have two 2D matrices A and B, I want to combine each column in with the corresponding column in B. For example:

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

Thus, I expect:

array([[1, 2, 1, 3],
       [1, 2, 1, 3]])
+4
source share
4 answers

Here is one with np.dstackand reshape-

np.dstack((A,B)).reshape(-1,A.shape[1]*2)

Run Example -

In [44]: A
Out[44]: 
array([[2, 7, 3, 0, 8],
       [1, 0, 6, 7, 6],
       [3, 4, 7, 7, 6],
       [0, 3, 7, 5, 4]])

In [45]: B
Out[45]: 
array([[8, 4, 3, 8, 0],
       [3, 1, 8, 8, 2],
       [8, 5, 8, 8, 4],
       [1, 0, 6, 1, 7]])

In [46]: np.dstack((A,B)).reshape(-1,A.shape[1]*2)
Out[46]: 
array([[2, 8, 7, 4, 3, 3, 0, 8, 8, 0],
       [1, 3, 0, 1, 6, 8, 7, 8, 6, 2],
       [3, 8, 4, 5, 7, 8, 7, 8, 6, 4],
       [0, 1, 3, 0, 7, 6, 5, 1, 4, 7]])
+1
source

You can try to combine the two arrays, then reorder the data with reshapeand 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]])
+3
source

(Fortran):

import numpy as np

def mix_arrays(a,b):
    return np.concatenate((a,b)).reshape(2,4, order='F')

A B:

>>> mix_arrays(A,B)
array([[1, 2, 1, 3],
       [1, 2, 1, 3]])
+2

. :

def mix_matrices(a,b):
    (ma,na) = a.shape
    (mb,nb) = b.shape
    if mb < ma:
        ma = mb
    c = np.zeros((ma,na+nb))
    c[:ma,::2] = a[:ma]
    c[:ma,1::2] = b[:ma]
    return c

:

>>> mix_matrices(A,B)
array([[ 1.,  2.,  1.,  3.],
       [ 1.,  2.,  1.,  3.]])
+1

Source: https://habr.com/ru/post/1671718/


All Articles