gpt4 book ai didi

python - 从列表理解输出有效地生成 numpy 数组?

转载 作者:行者123 更新时间:2023-11-28 21:25:41 24 4
gpt4 key购买 nike

有没有比使用 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])

最佳答案

我通常使用np.fromiter:

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

您不需要指定 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

关于python - 从列表理解输出有效地生成 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13876789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com