numpy - 将 Numpy 数组复制到内存 View

标签 numpy cython memoryview

我有一个 memoryviewnumpy数组并想复制另一个 numpy 的内容使用这个数组进入它 memoryview :

import numpy as np
cimport numpy as np

cdef double[:,::1] test = np.array([[0,1],[2,3]], dtype=np.double)

test[...] = np.array([[4,5],[6,7]], dtype=np.double)

但为什么这是不可能的呢?它让我一直在说

TypeError: only length-1 arrays can be converted to Python scalars Blockquote



如果我从 memoryview 复制它工作正常到 memoryview ,或来自 numpy数组到 numpy数组,但如何从 numpy 复制数组到 memoryview ?

最佳答案

这些任务有效:

cdef double[:,::1] test2d = np.array([[0,1],[2,3],[4,5]], dtype=np.double)
cdef double[:,::1] temp = np.array([[4,5],[6,7]], dtype=np.double)
test2d[...] = 4
test2d[:,1] = np.array([5],dtype=np.double)
test2d[1:,:] = temp
print np.asarray(test2d)

显示
[[ 4.  5.]
 [ 4.  5.]
 [ 6.  7.]]

我在 https://stackoverflow.com/a/30418422/901925 添加了一个答案在缩进的上下文中使用这种 memoryview 'buffer' 方法。
cpdef int testfunc1c(np.ndarray[np.float_t, ndim=2] A,
                    double [:,:] BView) except -1:
    cdef double[:,:] CView
    if np.isnan(A).any():
        return -1
    else:
        CView = la.inv(A)
        BView[...] = CView
        return 1

它不会执行其他发布者想要的无副本缓冲区分配,但它仍然是一个高效的内存 View 副本。

关于numpy - 将 Numpy 数组复制到内存 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30415082/

相关文章:

opencv - 将 cython 内存 View 传递给 OpenCV 函数

python - 类型错误 : 'numpy.float64' object does not support item assignment

python - 如何将一片 memoryview 转换为 C 字符串(unsigned char*)?

python - 如何不仅选择 `numpy.ndarray` 的最大值,而且选择 python 中的前 3 个最大值?

python - 加速cython代码

python-2.7 - 列表理解与 cython

python - Cython 的计算不正确

c++ - Cython:将 C++ `std::complex<double>` 的 vector 转换为 C `double complex`

python - Numpy 矩阵类 : Default constructor attributes for inherited class

python - 如果有多个元素,则查找 numpy 数组中最大元素的位置