直接从 __array_interface__ 创建 NumPy 数组

Dan*_*iel 6 python numpy pybinding

假设我有一本__array_interface__字典,我想从字典本身创建该数据的 numpy 视图。例如:

buff = {'shape': (3, 3), 'data': (140546686381536, False), 'typestr': '<f8'}
view = np.array(buff, copy=False)
Run Code Online (Sandbox Code Playgroud)

但是,这不适用于np.array将缓冲区或数组接口作为属性进行搜索。简单的解决方法可能如下:

class numpy_holder(object):
    pass

holder = numpy_holder()
holder.__array_interface__ = buff
view = np.array(holder, copy=False)
Run Code Online (Sandbox Code Playgroud)

这看起来有点绕。我是否缺少一种直接的方法来做到这一点?

hpa*_*ulj 5

更正 - 使用正确的“数据”值您的holder作品np.array

np.array肯定不会工作,因为它需要一个可迭代的东西,比如列表的列表,并解析各个值。

有一个低级构造函数,np.ndarray它接受一个缓冲区参数。还有一个np.frombuffer

但我的印象是,这x.__array_interface__['data'][0]是数据缓冲区位置的整数表示,而不是直接指向缓冲区的指针。我仅使用它来验证视图是否共享相同的数据缓冲区,而不是从中构造任何内容。

np.lib.stride_tricks.as_strided用于__array_interface__默认步幅和形状数据,但从数组而不是__array_interface__字典中获取数据。

===========

ndarray带有属性的示例.data

In [303]: res
Out[303]: 
array([[ 0, 20, 50, 30],
       [ 0, 50, 50,  0],
       [ 0,  0, 75, 25]])
In [304]: res.__array_interface__
Out[304]: 
{'data': (178919136, False),
 'descr': [('', '<i4')],
 'shape': (3, 4),
 'strides': None,
 'typestr': '<i4',
 'version': 3}
In [305]: res.data
Out[305]: <memory at 0xb13ef72c>
In [306]: np.ndarray(buffer=res.data, shape=(4,3),dtype=int)
Out[306]: 
array([[ 0, 20, 50],
       [30,  0, 50],
       [50,  0,  0],
       [ 0, 75, 25]])
In [324]: np.frombuffer(res.data,dtype=int)
Out[324]: array([ 0, 20, 50, 30,  0, 50, 50,  0,  0,  0, 75, 25])
Run Code Online (Sandbox Code Playgroud)

这两个数组都是视图。

好的,在你的holder课程中,我可以做同样的事情,使用它res.data作为数据缓冲区。您的班级创建了一个object exposing the array interface.

In [379]: holder=numpy_holder()
In [380]: buff={'data':res.data, 'shape':(4,3), 'typestr':'<i4'}
In [381]: holder.__array_interface__ = buff
In [382]: np.array(holder, copy=False)
Out[382]: 
array([[ 0, 20, 50],
       [30,  0, 50],
       [50,  0,  0],
       [ 0, 75, 25]])
Run Code Online (Sandbox Code Playgroud)