将行和列插入到numpy数组中

bla*_*laz 5 python numpy

我想在一个NumPy数组中插入多个行和列.

如果我有一个长方形数组n_a,例如:n_a = 3

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
Run Code Online (Sandbox Code Playgroud)

我想得到一个大小的新数组n_b,其中包含数组azeros(或任何其他1D长度数组n_b)在某些行和列上的索引,例如

index = [1, 3] 
Run Code Online (Sandbox Code Playgroud)

所以n_b = n_a + len(index).然后新的数组是:

b = np.array([[1, 0, 2, 0, 3],
              [0, 0, 0, 0, 0],
              [4, 0, 5, 0, 6],
              [0, 0, 0, 0, 0],
              [7, 0, 8, 0, 9]])
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何有效地做到这一点,假设更大的数组n_a远大于len(index).

编辑

结果:

import numpy as np
import random

n_a = 5000
n_index = 100

a=np.random.rand(n_a, n_a)
index = random.sample(range(n_a), n_index)
Run Code Online (Sandbox Code Playgroud)

Warren Weckesser的解决方案:0.208秒

Wim的解决方案:0.980秒

Ashwini Chaudhary的解决方案:0.955秒

谢谢你们!

War*_*ser 6

这是一种方法.它与@ wim的答案有一些重叠,但它使用索引广播来复制ab单个赋值.

import numpy as np

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

index = [1, 3]
n_b = a.shape[0] + len(index)

not_index = np.array([k for k in range(n_b) if k not in index])

b = np.zeros((n_b, n_b), dtype=a.dtype)
b[not_index.reshape(-1,1), not_index] = a
Run Code Online (Sandbox Code Playgroud)