Home > Software engineering >  Replace specific element in ndarray per condition
Replace specific element in ndarray per condition

Time:07-12

I have the following example array:

[[ 2  4 -1]
 [ 1 -1 -1]
 [ 2  4 -1]
 [ 0 -1 -1]
 [ 0  0  2]
 [ 2  4 -1]]

In each of the rows, if I have 0 twice, I need to replace the second one with -1 and move it to the end of the row, like this:

[[ 2  4 -1]
 [ 1 -1 -1]
 [ 2  4 -1]
 [ 0 -1 -1]
 [ 0  2 -1]
 [ 2  4 -1]]

I tried the following cycle:

for i in np.nditer(f_vars_r, op_flags = ['readwrite']):
    if i == 0 and i==0:
        i[...] == -1

I realize it cannot be complete, but at least I expected to receive some kind of error. Strangely, it passes without error but does nothing with the array. Any suggestions how the cycle can be re-worked to do the job will be greatly appreciated.

CodePudding user response:

Here's an approach that works on any size of sub-arrays.

The basic idea is to convert the numpy array to a list of lists; then loop over the list, for each sub-list get the indices of all the zeros; if there are two zeros in the sub-list, remove the zero with pop() and then append a -1 at the end

import numpy as np

x = np.array([[2, 0, 4, -1],
              [1, 0, -1, -1],
              [2, 0, 4, -1],
              [0, 0, -1, 2],
              [0, 0, 1, 2],
              [2, 0, 0, -1]])

# convert your numpy array to a list
x = x.tolist()

# iterate over the list (sub will contain the sublists)
for sub in x:
    # get the indices of zeros from sub
    zero_indices = [i for i, n in enumerate(sub) if n == 0]

    if len(zero_indices) == 2:
        sub.pop(zero_indices[1])  # remove the second zero
        sub.append(-1)  # add a -1 to the end

# convert the list back to a numpy array
x = np.array(x)
  • Related