8

I am trying to modify a NumPy array by adding a row of zeros after each row. My matrix has 491 rows and I should end up with a matrix that has 982 rows. I tried multiple ways using np.repeat, np.tile and so on to no avail.

Can anyone help me with this issue?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Liviu
  • 85
  • 1
  • 5

2 Answers2

16

You could do this by initialising a 982-row array first and then filling alternate rows, for example (5 columns):

a=np.zeros((982,5)) 
b=np.random.randint(0,100,(491,5)) # your 491 row matrix
a[::2] = b
Lee
  • 29,398
  • 28
  • 117
  • 170
  • @atom33ls how does it do it when you have a 3d shape of array.. i tried this: a = img64 N=1. out = np.zeros( (N+1)*np.array(a.shape)-N,dtype=a.dtype) print(a.shape,out.shape). The resulting array is not good since it also did it on the last dimension which I do not want to do.. any help on how to not do that – E B Feb 08 '19 at 00:31
  • Can anyone explain a[::2]? – tourism Jul 20 '19 at 13:50
  • @tourism every second row. It's [start:stop:step] See https://numpy.org/doc/stable/reference/arrays.indexing.html – Arigion Jul 28 '21 at 12:33
-1

Would like to add a snippet here to insert alternate rows of zeros and zeros in alternate columns as well. Though its not going to be useful now. But someone might find it useful as its a old post.

import numpy as np

a = np.array([[ 0.1,  0.2,  0.3],
       [ 1.1,  1.2,  1.3]])

b = np.zeros((a.shape[0]*2, a.shape[0]+a.shape[1]+1))

for i1,r in enumerate(a):
   for i2,e in enumerate(r):
     b[i1*2][i2*2] = e

print(b)
  • 4
    Using python loops is an extremely slow way to do anything in numpy. The old answer is much better, and can be used to do this as well. – Roobie Nuby May 18 '18 at 10:25
  • Taking this further, a[::2, ::2] = b would insert alternate rows/columns of zeros between rows and columns of data. – VictorLegros Oct 12 '19 at 15:42