简体   繁体   中英

Numpy array, insert alternate rows of zeros

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM