簡體   English   中英

將行和列插入到numpy數組中

[英]Inserting rows and columns into a numpy array

我想在NumPy數組中插入多個行和列。

如果我有一個長度為n_a的正方形數組,例如: n_a = 3

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

我想得到一個大小為n_b的新數組,其中包含帶索引的某些行和列的數組azeros (或任何其他長度為n_b 1D數組),例如

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_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)

Warren Weckesser的解決方案:0.208秒

Wim的解決方案:0.980秒

Ashwini Chaudhary的解決方案:0.955秒

謝謝你們!

這是一種方法。 它與@ 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

您可以通過在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

為什么你不能只切片/拼接 這具有零個的循環語句。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM