迭代numpy數組來填充python列表

[英]Iterate over numpy array to fill a python list


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.

我正在迭代一個numpy數組,通過每個元素應用一個函數,並將新值添加到列表中,以便我可以保留原始數據。

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 个解决方案

#1


2  

You could simply do:

你可以這樣做:

new_data = original_data/original_data.max()

Numpy already performs this operation element-wise.

Numpy已經按元素執行此操作。

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).

在你的代碼中有一個額外的緩慢來源:每個調用max(original_data)將導致對來自original_data的所有元素進行迭代,使得你的成本與O(n ^ 2)成比例。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/09/26/7254867a07dd984ced764edb137e106c.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com