简体   繁体   English

在Cython中使用2D NumPy数组可以避免使用Python吗?

[英]Can Python be avoided with 2D NumPy array in Cython?

I'm trying to minimize Python dependency in a while loop for large data series (>200MM values). 我正在尝试在大数据系列(> 200MM值)的while循环中最小化Python依赖性。

Comparing or setting a 1D NumPy array in Cython can be done completely with C, but doing the same with a 2D NumPy array devolves into expensive Python. 在Cython中比较或设置1D NumPy数组可以完全用C完成,但对2D NumPy数组做同样的操作会转化为昂贵的Python。

Does anyone know how to avoid this? 有谁知道如何避免这种情况?

Minimal code sample: 最小代码示例:

#!python
#cython: boundscheck=False
#cython: wraparound=False
#cython: cdivision=True

import numpy as np
cimport numpy as np

def sometest():
    cdef np.ndarray[np.float64_t, ndim=1] arr1d = np.zeros((10))
    cdef np.ndarray[np.float64_t, ndim=2] arr2d = np.zeros((10))

    if arr1d[0] > 1:
        arr1d[0] = 1

    if arr2d[0][0] > 1:
        arr2d[0][0] = 1

Cython annotation: Cython注释:

Cython注释

Expanded Cython annotation: 扩展的Cython注释:

扩展的Cython注释

Thank you in advance for any ideas. 提前感谢您的任何想法。

Thanks @hpaulj. 谢谢@hpaulj。

Accessing with arr2d[0,0] instead of arr2d[0][0] indeed does not degrade to Python. 使用arr2d [0,0]而不是arr2d [0] [0]进行访问确实不会降级为Python。

Updated code: 更新的代码:

#!python
#cython: boundscheck=False
#cython: wraparound=False
#cython: cdivision=True

import numpy as np
cimport numpy as np

def sometest():
    cdef np.ndarray[np.float64_t, ndim=1] arr1d = np.zeros((10))
    cdef np.ndarray[np.float64_t, ndim=2] arr2d = np.zeros((10, 10))

    if arr1d[0] > 1:
        arr1d[0] = 1

    if arr2d[0][0] > 1:
        arr2d[0][0] = 1

    if arr2d[0,0] > 1:
        arr2d[0,0] = 1

Cython annotation: Cython注释:

Cython注释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM