gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:09:21 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com