4

I'm iterating over a numpy array to apply a function through each element and add the new value to a list so I can keep the original data.

The problem is: it's kinda slow.

Is there a better way to do this (without changing the original array)?

import numpy as np
original_data = np.arange(0,16000, dtype = np.float32)
new_data = [i/max(original_data) for i in original_data]
print('done')

1 Answer 1

2

You could simply do:

new_data = original_data/original_data.max()

Numpy already performs this operation element-wise.

In your code there is an extra source of slowness: each call max(original_data) will result in an iteration over all elements from original_data, making your cost proportional to O(n^2).

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

1 Comment

Thank you very much. This approach will help alot.

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.