如何插入额外的所需列和行?
我有一个矩阵
any_matrix = np.array( [[1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12 ],
[13, 14, 15, 16 ]])
,我想插入所需的列,然后在之间行列,如下(如下所示)
[[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 ]]
我的尝试
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]]
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]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们必须同时使用np.insert和np.hstack进行此操作,
看起来有些麻烦,但它会起作用!
we have to use both np.insert and np.hstack for this operation
looks a little cumbersome, but it will work !!