How to replace the column of an array by the column of another array in python


Examples of how to replace the column of an array by the column of another array in python:

Array of same size

Let's try to replace column (1) of the N array by the column (2) of the M array:

>>> import numpy as np
>>> M = np.array([[2,7,1],[3,3,1],[5,4,2],[0,1,8]])
>>> M
array([[2, 7, 1],
       [3, 3, 1],
       [5, 4, 2],
       [0, 1, 8]])
>>> N = np.zeros((4,6))
>>> N[:,1] = M[:,2] 
>>> N
array([[ 0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.,  0.,  0.],
       [ 0.,  8.,  0.,  0.,  0.,  0.]])

Array of different sizes (N rows > M rows)

if array N has more lines than M array:

>>> import numpy as np
>>> M = np.array([[2,7,1],[3,3,1],[5,4,2],[0,1,8]])
>>> M
array([[2, 7, 1],
       [3, 3, 1],
       [5, 4, 2],
       [0, 1, 8]])
>>> N = np.zeros((8,6))
>>> M_dim_1 = M.shape[0]
>>> N_dim_1 = N.shape[0]
>>> M_dim_1
4
>>> N_dim_1
8
>>> if N_dim_1 > M_dim_1:
...     N[:M_dim_1,1] = M[:,2] 
... 
>>> N
array([[ 0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.,  0.,  0.],
       [ 0.,  8.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

Array of different sizes (N rows < M rows)

if array N has less lines than M array:

>>> N = np.zeros((3,6))
>>> N_dim_1 = N.shape[0]
>>> N_dim_1
3
>>> if N_dim_1 < M_dim_1:
...     N[:,1] = M[:N_dim_1,2] 
... 
>>> N
array([[ 0.,  1.,  0.,  0.,  0.,  0.],
      [ 0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.,  0.,  0.]])

References