直接从\u\u array_接口创建NumPy数组__

2024-05-12 12:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

这似乎有点迂回。我是不是错过了一个直截了当的方法?在


Tags: 数据方法numpyview视图falsedata字典
2条回答

另一种方法是:

import numpy as np


def arr_from_ptr(pointer, typestr, shape, copy=False,
                 read_only_flag=False):
    """Generates numpy array from memory address
    https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html

    Parameters
         
    pointer : int
        Memory address

    typestr : str
        A string providing the basic type of the homogenous array The
        basic string format consists of 3 parts: a character
        describing the byteorder of the data (<: little-endian, >:
        big-endian, |: not-relevant), a character code giving the
        basic type of the array, and an integer providing the number
        of bytes the type uses.

        The basic type character codes are:

        - t Bit field (following integer gives the number of bits in the bit field).
        - b Boolean (integer type where all values are only True or False)
        - i Integer
        - u Unsigned integer
        - f Floating point
        - c Complex floating point
        - m Timedelta
        - M Datetime
        - O Object (i.e. the memory contains a pointer to PyObject)
        - S String (fixed-length sequence of char)
        - U Unicode (fixed-length sequence of Py_UNICODE)
        - V Other (void * – each item is a fixed-size chunk of memory)

        See https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html#__array_interface__

    shape : tuple
        Shape of array.

    copy : bool
        Copy array.  Default False

    read_only_flag : bool
        Read only array.  Default False.
    """
    buff = {'data': (pointer, read_only_flag),
            'typestr': typestr,
            'shape': shape}

    class numpy_holder():
        pass

    holder = numpy_holder()
    holder.__array_interface__ = buff
    return np.array(holder, copy=copy)

用法:

^{pr2}$

更正-使用正确的“data”值,holdernp.array中工作:

np.array肯定行不通,因为它需要iterable,某些东西像列表列表,并解析各个值。在

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

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

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

==========

具有.data属性的ndarray示例:

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])

这两个数组都是视图。在

好的,对于您的holder类,我可以做同样的事情,使用这个res.data作为数据缓冲区。您的类创建一个object exposing the array interface。在

^{pr2}$

相关问题 更多 >