将Numpy数组复制到memoryview [英] Copy Numpy array to a memoryview

查看:181
本文介绍了将Numpy数组复制到memoryview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在numpy数组上有一个memoryview,并希望使用此memoryview将另一个numpy数组的内容复制到其中:

I have a memoryview on a numpy array and want to copy the content of another numpy array into it by using this 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)

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

But why is this not possible? It keeps me telling

TypeError:只能将长度为1的数组转换为Python标量 引用

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

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

It works fine if I copy from a memoryview to a memoryview, or from a numpy array to a numpy array, but how to copy from a numpy array to a 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缓冲区"方法.

I've added an answer at https://stackoverflow.com/a/30418422/901925 that uses this memoryview 'buffer' approach in a indented context.

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

它没有执行其他发布者想要的无副本缓冲区分配,但是它仍然是高效的memoryview副本.

It doesn't perform the copy-less buffer assignment that the other poster wanted, but it is still an efficient memoryview copy.

这篇关于将Numpy数组复制到memoryview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆