Home > Mobile >  How to insert extra desired column and row?
How to insert extra desired column and row?

Time:04-23

i have a matrix

any_matrix = np.array( [[1,     2,   3,    4   ],
                        [5,     6,   7,    8   ],
                        [9,    10,   11,  12   ],
                        [13,   14,   15,   16  ]])

and I want to insert desired column and row in between, like this( shown below )

  
[[1,   2,   0,   3,    4,  0   ],
[5,    6,   0,   7,    8,  0   ],
[0,    0,   1,   0,    0,  0   ],
[9,    10,  0,   11,  12,  0   ],
[13,   14,  0,   15,  16,  0   ],
[0,    0,   0,   0,    0,  1   ]]

my attempt

import numpy as np


any_matrix = np.array( [[1,     2,   3,    4   ],
                        [5,     6,   7,    8   ],
                        [9,    10,   11,  12   ],
                        [13,   14,   15,   16  ]])


desired_cols_ids = np.array([2, 4], dtype=np.int64)
zero_arr_row = np.zeros((1, any_matrix .shape[1]))
any_matrix  = np.insert(any_matrix , desired_cols_ids, zero_arr_row, axis = 0)
zero_arr_col = np.array([0,0,1,0,0,0]).reshape(6,1)
any_matrix  = np.insert(any_matrix , desired_cols_ids, zero_arr_col, axis=1)

print(any_matrix)

>>output

[[ 1  2  0  3  4  0]
 [ 5  6  0  7  8  0]
 [ 0  0  1  0  0  1]
 [ 9 10  0 11 12  0]
 [13 14  0 15 16  0]
 [ 0  0  0  0  0  0]]

CodePudding user response:

we have to use both np.insert and np.hstack for this operation

looks a little cumbersome, but it will work !!

import numpy as np

any_matrix = np.array( [[1,     2,   3,    4   ],
                        [5,     6,   7,    8   ],
                        [9,    10,   11,  12   ],
                        [13,   14,   15,   16  ]])


desired_cols_ids = np.array([2, 4], dtype=np.int64)
zero_arr_row = np.zeros((1, any_matrix .shape[1]))
any_matrix  = np.insert(any_matrix , desired_cols_ids, zero_arr_row, axis = 0)
print(any_matrix)

# Array to be added as column at the last
column_to_be_added = np.array([0,0,0,0,0,1])
 
# Adding last column to numpy array
any_matrix = np.hstack((any_matrix, np.atleast_2d(column_to_be_added).T))

# Adding column at second position to numpy array
desired_cols_ids_1 = np.array([2,], dtype=np.int64)
zero_arr_col = np.array([0,0,1,0,0,0]).reshape(6,1)
any_matrix = np.insert(any_matrix, desired_cols_ids_1, zero_arr_col, axis=1)                   
                   

print(any_matrix)


  • Related