Cython: Convert memory view to NumPy array

不想你离开。 提交于 2019-12-04 16:10:53

问题


How to convert a typed memoryview to an NumPy array in cython? The docs have

cimport numpy as np
import numpy as np

numpy_array = np.asarray(<np.int32_t[:10, :10]> my_pointer)

I took this for my case

np.asarray(<np.float_t[:, :]> my_memview)

Using this the compiler tells me:

Can only create cython.array from pointer or array

Copying or not is not so decicive. I couldn't find any help on this.


回答1:


You should just be able to use np.asarray directly on the memoryview itself, so something like:

np.asarray(my_memview)

should work. For example if your cython source file contains this:

import numpy as np
cimport numpy as np
def test(double[:,:] x):
    print type(x)
    print type(np.asarray(x))

Then after compiling it, you should be able to do the following from the python side:

a = np.random.normal(size=(5,5))
test(a)

Which produces the following output:

<type '_cython_magic_0182fca918bfa3618c3553e51b13e8ba._memoryviewslice'>
<type 'numpy.ndarray'>

Note: I'm using the cythonmagic extension for IPython.



来源:https://stackoverflow.com/questions/20978377/cython-convert-memory-view-to-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!