1

Let's say I have a 3d numpy ndarray with the shape 5x7x3

import numpy as np

arr = np.random.rand(5,7,3)

What I would like to do is:

  • Take every sub-array
  • Find out if the first value in a sub-array is larger than the sum of the last to elements.
  • If the condition is true then I would like to change of all three elements in the sub-array to the same value (eg. 2).

1 Answer 1

1

you can do something like this

import numpy as np

arr = np.random.randint(5,size=(5,7,3))
print(arr)
for i in range(len(arr)):
    for j in range(len(arr[i])):
        if arr[i][j][0]<arr[i][j][-1]+arr[i][j][-2]:
            arr[i][j]=[2,2,2]
print('updated array',arr)

output

[[[0 2 1]
  [0 2 3]
  [2 3 0]
  [1 0 0]
  [2 2 3]
  [1 4 2]
  [3 3 4]]

 [[3 1 0]
  [1 4 3]
  [0 1 1]
  [4 2 2]
  [1 1 0]
  [2 1 3]
  [0 4 3]]

 [[2 3 1]
  [0 4 4]
  [2 1 2]
  [4 3 2]
  [2 3 4]
  [0 2 3]
  [3 4 1]]

 [[0 4 1]
  [2 0 0]
  [2 2 3]
  [0 2 3]
  [0 4 4]
  [0 4 0]
  [1 2 3]]

 [[4 0 0]
  [3 4 1]
  [2 2 4]
  [3 0 4]
  [1 2 3]
  [4 3 1]
  [4 3 4]]]
dsfs [[[2 2 2]
  [2 2 2]
  [2 2 2]
  [1 0 0]
  [2 2 2]
  [2 2 2]
  [2 2 2]]

 [[3 1 0]
  [2 2 2]
  [2 2 2]
  [4 2 2]
  [1 1 0]
  [2 2 2]
  [2 2 2]]

 [[2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]]

 [[2 2 2]
  [2 0 0]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]]

 [[4 0 0]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [2 2 2]
  [4 3 1]
  [2 2 2]]]
Sign up to request clarification or add additional context in comments.

2 Comments

I can see that it would work, but i was hoping that there was a faster build-in funktion.
I believe ur case is custom requirememt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.