Home > OS >  Iterating over 3D numpy array, creating a copy and set new values
Iterating over 3D numpy array, creating a copy and set new values

Time:08-14

Hello python community,

I am new to python and playing around with numpy arrays and have a question. E.g. I have this 3D array (in reality the array is much much bigger)

input = np.array([[[0,0,1,1,2,2],[0,0,1,1,2,2],[0,0,1,1,2,2]],[[0,0,1,1,2,2],[0,0,1,1,2,2],[0,0,1,1,2,2]]])

and I want to replace the 2s with 0s to get:

result = np.array([[[0,0,1,1,0,0],[0,0,1,1,0,0],[0,0,1,1,0,0]],[[0,0,1,1,0,0],[0,0,1,1,0,0],[0,0,1,1,0,0]]])

Is there an efficient/fast way to do this? The only thing I know is to iterate with for x in range ... but that's probably not very efficient is it?

CodePudding user response:

Try:

inp = np.array(
    [
        [[0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2]],
        [[0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2]],
    ]
)

inp = np.where(inp == 2, 0, inp)
print(inp)

Prints:

[[[0 0 1 1 0 0]
  [0 0 1 1 0 0]
  [0 0 1 1 0 0]]

 [[0 0 1 1 0 0]
  [0 0 1 1 0 0]
  [0 0 1 1 0 0]]]

CodePudding user response:

you can filter to indices that are 2 and replace:

arr = np.array([[[0,0,1,1,2,2],[0,0,1,1,2,2],[0,0,1,1,2,2]],[[0,0,1,1,2,2],[0,0,1,1,2,2],[0,0,1,1,2,2]]])
arr[arr == 2] = 0

output:

array([[[0, 0, 1, 1, 0, 0],
        [0, 0, 1, 1, 0, 0],
        [0, 0, 1, 1, 0, 0]],

       [[0, 0, 1, 1, 0, 0],
        [0, 0, 1, 1, 0, 0],
        [0, 0, 1, 1, 0, 0]]])
  • Related