栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从numpy数组列表创建numpy数组的Python方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从numpy数组列表创建numpy数组的Python方法

假设您知道最终的数组

arr
永远不会大于5000x10。然后,您可以预分配最大大小的数组,在遍历循环时将其填充数据,然后
arr.resize
在退出循环后将其缩减为发现的大小。

下面的测试表明,无论数组的最终大小如何,这样做都会比构造中间python列表快一点。

同样,

arr.resize
取消分配未使用的内存,因此最终的(虽然可能不是中间的)内存占用空间小于所使用的内存占用空间
python_lists_to_array

这表明

numpy_all_the_way
速度更快:

% python -mtimeit -s"import test" "test.numpy_all_the_way(100)"100 loops, best of 3: 1.78 msec per loop% python -mtimeit -s"import test" "test.numpy_all_the_way(1000)"100 loops, best of 3: 18.1 msec per loop% python -mtimeit -s"import test" "test.numpy_all_the_way(5000)"10 loops, best of 3: 90.4 msec per loop% python -mtimeit -s"import test" "test.python_lists_to_array(100)"1000 loops, best of 3: 1.97 msec per loop% python -mtimeit -s"import test" "test.python_lists_to_array(1000)"10 loops, best of 3: 20.3 msec per loop% python -mtimeit -s"import test" "test.python_lists_to_array(5000)"10 loops, best of 3: 101 msec per loop

这显示

numpy_all_the_way
使用更少的内存:

% test.pyInitial memory usage: 19788After python_lists_to_array: 20976After numpy_all_the_way: 20348

test.py:

import numpy as npimport osdef memory_usage():    pid = os.getpid()    return next(line for line in open('/proc/%s/status' % pid).read().splitlines()     if line.startswith('VmSize')).split()[-2]N, M = 5000, 10def python_lists_to_array(k):    list_of_arrays = list(map(lambda x: x * np.ones(M), range(k)))    arr = np.array(list_of_arrays)    return arrdef numpy_all_the_way(k):    arr = np.empty((N, M))    for x in range(k):        arr[x] = x * np.ones(M)    arr.resize((k, M))    return arrif __name__ == '__main__':    print('Initial memory usage: %s' % memory_usage())    arr = python_lists_to_array(5000)    print('After python_lists_to_array: %s' % memory_usage())    arr = numpy_all_the_way(5000)    print('After numpy_all_the_way: %s' % memory_usage())


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号