How to replace the row of an array by the row of another array with numpy

Published: January 17, 2019

DMCA.com Protection Status

Examples of how to replace array line by another array line with numpy:

Array of same size

let's try to replace array N line 2 by array M line 2:

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

Array of different sizes (N column > M column)

if dimension 2 of array M is not the same dimension that N:

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

Array of different sizes (N column < M column)

>>> N = np.zeros((6,2))
>>> N_dim_2 = N.shape[1]
>>> N_dim_2
2
>>> if N_dim_2 < M_dim_2:
...     N[2,:] = M[2,:N_dim_2] 
... 
>>> N
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 5.,  4.],
       [ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

References