0

I have two numpy arrays, array_one which is NxM and array_two which is NxMx3, and I'd like to change the value of the last element in each row of array_two, based on values from array_one, like this:

array_two[i, j, -1] = foo(array_one[i,j])

where foo returns a value based on a computation on an element from array_one.

Is there a way to avoid manually looping over the arrays and speed up this process using numpy functions?

3
  • It depends on whether your foo can be vectorized. Commented Sep 22, 2022 at 14:16
  • Yes, and no. The answer is much depend on how you write the foo function. Does it support passing numpy array? for example, array_two[:,:,-1] = np.sum(array_one) would work, but array_two[:,:,-1] = math.sin(array_one) wouldn't. Commented Sep 22, 2022 at 14:17
  • First of all thanks to both of you. The foo function maps the received value between 0 and 255 based on predefined min/max levels. How could I modify it so that it can vectorized? Commented Sep 22, 2022 at 14:23

1 Answer 1

1

Example showing use of np.vectorize to achieve what you had in mind.

replace square with your foo and you should be in business.

import numpy as np

array_3d = np.ones((2,3,2))

array_2d = np.random.randn(2,3)

def square(x):
    return x**2

square_all = np.vectorize(square)

array_3d[:,:,-1] = square_all(array_2d)
print(f'{array_3d[:,:,:]=}')
Sign up to request clarification or add additional context in comments.

Comments

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.