从列表推导输出中有效地生成numpy数组?

rya*_*lon 2 python numpy

有没有比使用numpy.asarray()list?形式从输出生成数组更有效的方法?

这似乎是复制内存中的所有内容,这对于非常大的数组来说似乎并不高效.

(更新)示例:

import numpy as np
a1 = np.array([1,2,3,4,5,6,7,8,9,10]) # pretend this has thousands of elements
a2 = np.array([3,7,8])

results = np.asarray([np.amax(np.where(a1 > element)) for element in a2])
Run Code Online (Sandbox Code Playgroud)

use*_*424 5

我通常使用np.fromiter:

results = np.fromiter((np.amax(np.amax(np.where(a1 > element)) for element in a2), dtype=int, count=len(a2))
Run Code Online (Sandbox Code Playgroud)

您不需要指定,count但它允许numpy预分配数组.以下是我在https://www.pythonanywhere.com/try-ipython/上做的一些时间:

In [8]: %timeit np.asarray([np.amax(np.where(a1 > element)) for element in a2])                                 
1000 loops, best of 3: 161 us per loop

In [10]: %timeit np.frompyfunc(lambda element: np.amax(np.where(a1 > element)),1,1)(a2,out=np.empty_like(a2))   
10000 loops, best of 3: 123 us per loop

In [13]: %timeit np.fromiter((np.amax(np.where(a1 > element)) for element in a2),dtype=int, count=len(a2))
10000 loops, best of 3: 111 us per loop
Run Code Online (Sandbox Code Playgroud)