简体   繁体   English

Numpy数组,插入备用的零行

[英]Numpy array, insert alternate rows of zeros

I am trying to modify a NumPy array by adding a row of zeros after each row. 我试图通过在每行之后添加一行零来修改NumPy数组。 My matrix has 491 rows and I should end up with a matrix that has 982 rows. 我的矩阵有491行,我最终应该有一个982行的矩阵。 I tried multiple ways using np.repeat , np.tile and so on to no avail. 我试过多种方法使用np.repeatnp.tile等无济于事。

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): 您可以通过首先初始化982行数组然后填充备用行来完成此操作,例如(5列):

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. 想在此处添加一个片段,以便在备用列中插入备用的0和0行。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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