Python 将行和列插入numpy数组

Python 将行和列插入numpy数组,python,numpy,Python,Numpy,我想在NumPy数组中插入多个行和列 如果我有一个长度为n_a的正方形数组,例如:n_a=3 a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 我想得到一个大小为n_b的新数组,它包含数组a和0(或任何其他长度为n_b的1D数组)和索引,例如 index = [1, 3] 所以n_b=n_a+len(索引)。那么新阵列是: b = np.array([[1, 0, 2, 0, 3],

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

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

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
我想得到一个大小为
n_b
的新数组,它包含数组
a
0
(或任何其他长度为
n_b
1D
数组)和索引,例如

index = [1, 3] 
所以
n_b=n_a+len(索引)
。那么新阵列是:

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]])
我的问题是,如何有效地做到这一点,假设通过更大的数组
n\u 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)
沃伦·韦克瑟的解决方案:0.208秒

wim的解决方案:0.980秒

Ashwini Chaudhary溶液:0.955 s


谢谢大家

您可以通过在
a
上应用两个
numpy.insert
调用来执行此操作:

>>> a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
>>> indices = np.array([1, 3])
>>> i = indices - np.arange(len(indices))
>>> np.insert(np.insert(a, i, 0, axis=1), i, 0, axis=0)
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]])

由于索引返回的是副本而不是视图, 我只能分两步思考如何做到这一点。也许一个裸体巫师知道一个更好的方法

给你:

import numpy as np

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

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

non_index = [x for x in xrange(N) if x not in index]

b = np.zeros((N,n), a.dtype)
b[non_index] = a

a = np.zeros((N,N), a.dtype)
a[:, non_index] = b

这里有一个方法。它与@wim的答案有些重叠,但它使用索引广播将
a
复制到
b
,只需一个赋值

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
你为什么不能就这样?这有零个循环或for语句

xlen = a.shape[1]
ylen = a.shape[0]
b = np.zeros((ylen * 2 - ylen % 2, xlen * 2 - xlen % 2))  #accomodates both odd and even shapes
b[0::2,0::2] = a

这是可行的,但是我正在寻找一个更通用的方法来说明创建空数组后要做什么(arr[::2,::2]=a仅适用于这种情况)。对于这种3x3大小,此解决方案的速度要慢5-10倍。但对于100x100矩阵,它比其他2(2x)矩阵更快。内部
insert
使用构建大型填充矩阵,然后用旧数据填充它。因此,速度差异必须(主要)来自于首先对行进行操作,然后对列进行操作。@Warren Weckesser的解决方案速度更快。-(-1)我被纠正了,我认为
np.insert
必须移动大量数据,但它的实现似乎比我想象的要好。是的,很好!这是最好的方法,这就是我试图用
b[not_index,:][:,not_index]=a
(这不起作用)所做的。你的方法应该比我的快两倍左右。