Numpy 数组:遍历列并根据下一个值更改值

Numpy array: iterate through column and change value depending on the next value

我有一个像这样的 numpy 数组:

data = np.array([
     [1,2,3],
     [1,2,3],
     [1,2,101],
     [4,5,111],   
     [4,5,6], 
     [4,5,6], 
     [4,5,101], 
     [4,5,112], 
     [4,5,6], 
     ])

在第三列中,如果下一个是 101,我希望将值替换为 10001。这将导致这样的数组:

data = np.array([
     [1,2,3],
     [1,2,10001],
     [1,2,101],
     [4,5,111],   
     [4,5,6], 
     [4,5,10001], 
     [4,5,101], 
     [4,5,112], 
     [4,5,6], 
     ])

我试过这个,我确信它会起作用,但它不起作用...

dith = np.nditer(data[:, 2], op_flags=['readwrite'])
for i in dith:
    if i+1 == 3:
        i[...] = 10001

如果有人可以帮助解决这个问题,那就太好了。

indices_of_101 = np.where(data[:, 2] == 101)[0]
if indices_of_101[0] = 0:  # taking into accound boundary problem
    indices_of_101 = indices_of_101[1:]
data[:, indices_of_101-1] = 10001

试试这个 -

data[np.roll(data==101,-1,0)] = 10001
array([[    1,     2,     3],
       [    1,     2, 10001],
       [    1,     2,   101],
       [    4,     5,   111],
       [    4,     5,     6],
       [    4,     5, 10001],
       [    4,     5,   101],
       [    4,     5,   112],
       [    4,     5,     6]])

此处唯一的假设是您的第一行不包含 101


如果矩阵的第一行可能出现 101 的情况,请尝试下面的方法。

idx = np.vstack([np.roll(data==101,-1,0)[:-1], np.array([False, False, False])])
data[idx] = 10001
array([[    1,     2,     3],
       [    1,     2, 10001],
       [    1,     2,   101],
       [    4,     5,   111],
       [    4,     5,     6],
       [    4,     5, 10001],
       [    4,     5,   101],
       [    4,     5,   112],
       [    4,     5,     6]])