在numpy的2d数组中的特定位置插入一行?

时间:2023-01-27 21:34:41

I have a 2d array in numpy where I want to insert a new row. Following question Numpy - add row to array can help. We can use numpy.vstack, but it stacks at the start or at the end. Can anyone please help in this regard.

我有一个ndy的2d数组,我想插入一个新行。以下问题Numpy - 向数组添加行可以提供帮助。我们可以使用numpy.vstack,但它在开始或结束时堆叠。任何人都可以在这方面提供帮助。

1 个解决方案

#1


36  

You are probably looking for numpy.insert

您可能正在寻找numpy.insert

>>> import numpy as np
>>> a = np.zeros((2, 2))
>>> a
array([[ 0.,  0.],
       [ 0.,  0.]])
# In the following line 1 is the index before which to insert, 0 is the axis.
>>> np.insert(a, 1, np.array((1, 1)), 0)  
array([[ 0.,  0.],
       [ 1.,  1.],
       [ 0.,  0.]])
>>> np.insert(a, 1, np.array((1, 1)), 1)
array([[ 0.,  1.,  0.],
       [ 0.,  1.,  0.]])

#1


36  

You are probably looking for numpy.insert

您可能正在寻找numpy.insert

>>> import numpy as np
>>> a = np.zeros((2, 2))
>>> a
array([[ 0.,  0.],
       [ 0.,  0.]])
# In the following line 1 is the index before which to insert, 0 is the axis.
>>> np.insert(a, 1, np.array((1, 1)), 0)  
array([[ 0.,  0.],
       [ 1.,  1.],
       [ 0.,  0.]])
>>> np.insert(a, 1, np.array((1, 1)), 1)
array([[ 0.,  1.,  0.],
       [ 0.,  1.,  0.]])