python - Numpy - 从数组列表创建数组的最有效方法
问题描述
我有一个程序,其当前的性能瓶颈涉及从相对较长的扁平数组的相对较短列表中创建一个新数组:
num_arrays = 5
array_length = 1000
arrays = [np.random.random((array_length, )) for _ in range(num_arrays)]
new_array = np.array(arrays)
换句话说,将n
shape 数组堆叠(s,)
成new_array
of shape (n, s)
。
我正在寻找最有效的方法来计算这个,因为这个操作重复了数百万次。
我测试了两种简单方法的性能:
%timeit np.array(arrays)
>>> 3.6 µs ± 67.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.stack(arrays)
>>> 9.61 µs ± 133 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
我目前正在使用np.array(arrays)
,但我想知道是否有更有效的方法来做到这一点。
一些可能有帮助的细节:
- 数组的长度在程序的整个运行期间都是固定的,例如
1000
. - 数组的数量通常很少,通常是
<=5
. 在整个程序运行过程中(即每创建约 1000 个此类数组),可以在检查点获得此上限,但不能提前。
解决方案
推荐阅读
- android - 颤振警报在后台和锁定模式下不触发
- c - 为什么我的代码在 9 之后没有生成阶乘?
- c# - Xamarin.Google.UserMessagingPlatform 指南?
- .htaccess - 棘手的 .htaccess mod_rewrite 语法问题
- python - Python 虚拟环境中的 Wexpect
- python - 将 Pandas 数据框拆分为波段
- sql - 将字段从一个表迁移到另一个表
- flutter - Dart Null 安全性:不能无条件调用方法“[]”,因为接收者可以为“null”
- azure - AADSTS50011:请求中指定的回复 URL 与为应用程序配置的回复 URL 不匹配:'cf710c6e-dfcc-
- postgresql - 针对 RHEL Little endian 将 PostgreSQL 从 9.5 升级到 13.3 的步骤