高效的Python数组转numpy数组转换
我从Python的标准库中得到了一个很大的数组(一个12百万像素的图像),这个数组的格式是普通的数组。因为我想对这个数组进行一些操作,所以我想把它转换成numpy数组。我尝试了以下方法:
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中用循环处理是差不多的。
有没有更高效的方法来进行这个转换呢?
2 个回答
5
asarray(x)
几乎总是处理任何类似数组的对象时最好的选择。
array
和 fromiter
的速度比较慢,因为它们会进行一次复制。使用 asarray
可以避免这个复制过程:
>>> import array
>>> import numpy as np
>>> test = array.array('d', [0]*12000000)
# very slow - this makes multiple copies that grow each time
>>> %timeit np.fromiter(test, dtype=test.typecode)
626 ms ± 3.97 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# fast memory copy
>>> %timeit np.array(test)
63.5 ms ± 639 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# which is equivalent to doing the fast construction followed by a copy
>>> %timeit np.asarray(test).copy()
63.4 ms ± 371 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# so doing just the construction is way faster
>>> %timeit np.asarray(test)
1.73 µs ± 70.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# marginally faster, but at the expense of verbosity and type safety if you
# get the wrong type
>>> %timeit np.frombuffer(test, dtype=test.typecode)
1.07 µs ± 27.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
64
np.array(test) # 1.19s
np.fromiter(test, dtype=int) # 1.08s
np.frombuffer(test) # 459ns !!!
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。