6 c python arrays numpy cython
当在Cython中将numpy.ndarrays传递给只处理连续数组的C函数时,执行以下操作之间是否有区别:
np.ndarray[double, ndim=1, mode="c"] arr = np.ascontiguousarray(np.array([1,2,3],dtype=float))
Run Code Online (Sandbox Code Playgroud)
和
np.ndarray[double, ndim=1, mode="c"] arr = np.asarray(np.array([1,2,3],dtype=float), order="c")
Run Code Online (Sandbox Code Playgroud)
都有必要吗?是否np.ascontiguous
暗示数组将采用可以通过mode=c
声明分配给数组的格式?
该文档的ascontiguousarray
状态,它会返回一个C有序阵列,所以是的,如果你使用ascontiguousarray
,你可以假设数据是有序的c
模式.
然后回答两者之间的差异,我们可以阅读来源.
asarray
(链接)这样做:
return array(a, dtype, copy=False, order=order)
Run Code Online (Sandbox Code Playgroud)
ascontiguousarray
(链接)这样做:
return array(a, dtype, copy=False, order='C', ndmin=1)
Run Code Online (Sandbox Code Playgroud)
因此,当您调用asarray时order='C'
,唯一的区别ascontiguousarray
是您选择ndmin的默认值,即0
.当您在单个数字而不是列表上使用这两种方法时,这归结为这种差异:
print asarray(4,dtype='float',order='c').shape
()
print ascontiguousarray(4,dtype='float').shape
(1,)
Run Code Online (Sandbox Code Playgroud)
这取决于你,但我更喜欢ascontiguousarray
,因为我经常依赖于处理数组的shape属性的可能性,并期望它是非空的.从某种意义上说,它就像atleast1d
在同一时间打电话一样.
你应该能够这样做:
np.ndarray[double, ndim=1, mode="c"] arr = np.array([1,2,3], dtype=np.float64, order="c")
Run Code Online (Sandbox Code Playgroud)
从文档中np.array
:
order : {'C', 'F', 'A'}, optional
Specify the order of the array. If order is 'C' (default), then the
array will be in C-contiguous order (last-index varies the
fastest). If order is 'F', then the returned array
will be in Fortran-contiguous order (first-index varies the
fastest). If order is 'A', then the returned array may
be in any order (either C-, Fortran-contiguous, or even
discontiguous).
Run Code Online (Sandbox Code Playgroud)
np.ascontiguousarray
我的理解是,只有当您尝试传递的数组是从另一个数组的某些不连续切片生成时才需要使用。如果您从头开始创建数组,则没有必要。
例如:
a = np.arange(10)
a.flags['C_CONTIGUOUS'] # True
b = a[::2]
b.flags['C_CONTIGUOUS'] # False
c = np.ascontiguousarray(b)
c.flags['C_CONTIGUOUS'] # True
Run Code Online (Sandbox Code Playgroud)
另外,也许可以考虑使用类型化的内存视图接口
double[::1] arr = np.array([1,2,3], dtype=np.float64)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4117 次 |
最近记录: |