将numpy数组转换为标准库数组而不进行内存分配

时间:2016-12-23 11:56:12

标签: python arrays numpy

有没有办法将numpy ndarray(numpy.array)转换为标准库数组(array.array)而无需重新分配数据?

对于记录,可以使用缓冲区接口将array.array转换为ndarray,所以我希望可以绕道:

import numpy
import array
a_std = array.array('d', [1, 2, 3])
a_np = numpy.ndarray(shape=(3, ), buffer=a_std, dtype='d')
a_np[0] = 666.
assert a_std[0] == 666.

1 个答案:

答案 0 :(得分:0)

到目前为止,我最好的猜测是不可能:内存重新分配无法避免。

我发现将numpy数组转换为array.array的最快方法是使用ndarray.tobytes()

import numpy
import array
a_np = np.random.uniform(size=(10 * 1000 * 1000))  # 76 MiB
a_std = array.array('d', a_np.tobytes())

numpy.testing.assert_allclose(a_std, a_np)

使用其他方法快速进行基准测试(使用IPython):

%timeit a_std = array.array('d', a_np.tobytes())
10 loops, best of 3: 56.8 ms per loop

%timeit a_std = array.array('d', a_np.data)
1 loop, best of 3: 946 ms per loop

%timeit a_std = array.array('d', a_np)
1 loop, best of 3: 1.17 s per loop
相关问题