简体   繁体   English

如何插入额外的所需列和行?

[英]How to insert extra desired column and row?

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]]

we have to use both np.insert and np.hstack for this operation我们必须同时使用 np.insert 和 np.hstack 来执行此操作

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)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM