Cython:将内存视图转换为NumPy数组 [英] Cython: Convert memory view to NumPy array
问题描述
如何在cython中将类型化的memoryview转换为NumPy数组?文档有
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)
我为我的案件接受了
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.
推荐答案
您应该只能够直接在memoryview本身上使用np.asarray
,所以类似:
You should just be able to use np.asarray
directly on the memoryview itself, so something like:
np.asarray(my_memview)
应该工作.例如,如果您的cython源文件包含以下内容:
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))
然后在编译它之后,您应该能够从python方面执行以下操作:
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)
将产生以下输出:
<type '_cython_magic_0182fca918bfa3618c3553e51b13e8ba._memoryviewslice'>
<type 'numpy.ndarray'>
注意:我正在为IPython使用cythonmagic扩展.
Note: I'm using the cythonmagic extension for IPython.
这篇关于Cython:将内存视图转换为NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!