Insert rows and columns into a numpy array

I would like to insert some rows and columns into a numpy array.

If I have a square array of length n_a, for example: n_a = 3

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

and I would like to get a new array with size n_b that contains an array a and zeros (or any other 1-d array of length n_b) for specific rows and columns with indexes, for example.

 index = [1, 3] 

so n_b = n_a + len (index). Then a new array:

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

So my question is how to do this efficiently, based on the assumption that the larger n_a arrays are much larger than len (index).

EDIT

Results for:

 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 Walkesser Solution: 0.208 s

Wim solution: 0.980 s

Ashwini Chaudhary Solution: 0.955 s

Thanks everyone!

+5
source share
4 answers

Here is one way to do it. It has some overlap with @wim's answer, but it uses index broadcast to copy a to b with a single assignment.

 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 
+6
source

You can do this by applying two calls to numpy.insert on a :

 >>> 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]]) 
+3
source

Since fancy indexing returns a copy instead of a view, I can only think about how to do this in a two-step process. Maybe the numpy master knows a better way ...

Here you go:

 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 
+1
source

Why can't you just Slice / splice ? This has zero cycles or for operators.

 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 
0
source

Source: https://habr.com/ru/post/1206625/


All Articles