高效的python数组到numpy数组的转换 [英] efficient python array to numpy array conversion
本文介绍了高效的python数组到numpy数组的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从 python 标准库中获得了一个数组格式的大数组(12 Mpix 的图像).由于我想对这些数组执行操作,我希望将其转换为一个 numpy 数组.我尝试了以下方法:
I get a big array (image with 12 Mpix) in the array format from the python standard lib. Since I want to perform operations on those array, I wish to convert it to a numpy array. I tried the following:
import numpy
import array
from datetime import datetime
test = array.array('d', [0]*12000000)
t = datetime.now()
numpy.array(test)
print datetime.now() - t
我在一两秒之间得到一个结果:相当于python中的一个循环.
I get a result between one or two seconds: equivalent to a loop in python.
有没有更有效的方法来进行这种转换?
Is there a more efficient way of doing this conversion?
推荐答案
np.array(test) # 1.19s
np.fromiter(test, dtype=int) # 1.08s
np.frombuffer(test) # 459ns !!!
这篇关于高效的python数组到numpy数组的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文