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]])>>> Marray([[2, 7, 1],[3, 3, 1],[5, 4, 2],[0, 1, 8]])>>> N = np.zeros((4,6))>>> N[:,1] = M[:,2]>>> Narray([[ 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]])>>> Marray([[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_14>>> N_dim_18>>> if N_dim_1 > M_dim_1:... N[:M_dim_1,1] = M[:,2]...>>> Narray([[ 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_13>>> if N_dim_1 < M_dim_1:... N[:,1] = M[:N_dim_1,2]...>>> Narray([[ 0., 1., 0., 0., 0., 0.],[ 0., 1., 0., 0., 0., 0.],[ 0., 2., 0., 0., 0., 0.]])
References
| Links | Site |
|---|---|
| Modify a particular row/column of a NumPy array | stackoverflow |
| Numpy replace specific rows and columns of one array with specific rows and columns of another array | stackoverflow |
