将行和列插入numpy数组

2024-04-19 21:52:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

index = [1, 3] 

所以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]])

我的问题是,在假设大数组n_alen(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.208s

wim解决方案:0.980 s

Ashwini Chaudhary的解决方案:0.955秒

谢谢大家!


Tags: importnumpy编辑indexlennpzeros情况
1条回答
网友
1楼 · 发布于 2024-04-19 21:52:14

这里有一种方法。它与@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
网友
2楼 · 发布于 2024-04-19 21:52:14

因为花式索引返回的是副本而不是视图, 我只能在两步的过程中思考如何去做。也许一个裸体巫师知道更好的方法。。。

给你:

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
网友
3楼 · 发布于 2024-04-19 21:52:14

您可以通过对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]])

相关问题 更多 >