0

I have a 3d array of dimension (1000, 300, 3), my_3d_array.

I want to modify each sample if this array then replace the old version with the modified one. In another word, I want to take the 1st example (300, 3) (lets called it old sample) apply some modification to it by calling a function called my_function, then the obtained new one will replace the old sample in my_3d_array, and so on. How can we do it please?

1 Answer 1

1

I'm not exactly sure this is what you want, but you can use the normal indexing notation:

# just an example array
my_3d_array = np.random.random((1000,300,3))

# extract the old sample
old_sample = my_3d_array[0,:,:]

# transform the sample
new_sample = my_function(old_sample)

# write the sample back to the original array
my_3d_array[0,:,:] = new_sample

If you want to do the same transformation for all samples it might be beneficial to vectorize my_function to process all samples at once instead of using a python loop.

Sign up to request clarification or add additional context in comments.

5 Comments

In general, this is the solution I'm looking for.It works for one sample. but I am looking if i can apply my function to all the 1000 samples one shot.
Is using a for loop over the first dimension of the array not an option?
using a loop will be inefficient since my_3d_array can be a huge array.
There are helper functions in numpy, e.g. apply_along_axis and vectorize numpy.org/doc/stable/reference/routines.functional.html. These could be used, but i doubt that they will give a significant performance boost because they also have to call your python function as many times as there are samples in your array. If my_function only uses numpy functions you can try to vectorize the function directly, this would probably give the best performance.
my_function uses np.random.normal(loc=0, scale=scale_value, size=sample.shape), and some times it uses np.matmul(). So I think vectorizing my_function is the best solution

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.