Iterate over a numpy array to populate a python list.

I repeat the numpy array to apply the function through each element and add a new value to the list to preserve the original data.

The problem is that it is 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')
+4
source share
1 answer

You can simply do:

new_data = original_data/original_data.max()

Numpy is already performing this operation by type.

There is an additional source of slowness in your code : each call max(original_data)will lead to iterating over all elements from original_data, which will make your cost proportional O(n^2).

+2
source

Source: https://habr.com/ru/post/1609098/


All Articles