在numpy数组列中插入一个值并保持相同的大小/行值

时间:2023-02-08 13:17:54

The title is not the best but essentially I need to insert a value at (y,x) and shift the column until -1 is met where I insert a new value and delete -1. Here is an example to insert (100) at (2,1):

标题不是最好的,但基本上我需要在(y,x)处插入一个值并移动列直到满足-1,我插入一个新值并删除-1。以下是在(2,1)处插入(100)的示例:

b = np.array([[1,-1,3],
     [2,5,6],
     [6,8,9],
     [10,4,3])

would become:

b = np.array([[1,5,3],
     [2,8,6],
     [6,100,9],
     [10,4,3]])

This example is for a case where I need to insert at a column but eventually I'll have to do it for rows as well. Numpy arrays may not be the best DS for this so if you have a better idea, dont hesitate. Thank you!

这个例子适用于我需要在列中插入但最终我还必须为行执行此操作的情况。 Numpy数组可能不是最好的DS,所以如果你有更好的想法,不要犹豫。谢谢!

1 个解决方案

#1


0  

First, let's import numpy and define your array:

首先,让我们导入numpy并定义你的数组:

>>> import numpy as np
>>> b = np.array([[1,-1,3], [2,5,6], [6,8,9], [10,4,3]])

Now, to do your substitution, try:

现在,要做替换,请尝试:

>>> b[:, 1] = np.concatenate((b[1:3, 1], [100], b[3:, 1]))
>>> b
array([[  1,   5,   3],
       [  2,   8,   6],
       [  6, 100,   9],
       [ 10,   4,   3]])

#1


0  

First, let's import numpy and define your array:

首先,让我们导入numpy并定义你的数组:

>>> import numpy as np
>>> b = np.array([[1,-1,3], [2,5,6], [6,8,9], [10,4,3]])

Now, to do your substitution, try:

现在,要做替换,请尝试:

>>> b[:, 1] = np.concatenate((b[1:3, 1], [100], b[3:, 1]))
>>> b
array([[  1,   5,   3],
       [  2,   8,   6],
       [  6, 100,   9],
       [ 10,   4,   3]])