Creating a NumPy array directly from __array_interface__

后端 未结 2 1057
情话喂你
情话喂你 2020-12-21 04:35

Suppose I have an __array_interface__ dictionary and I would like to create a numpy view of this data from the dictionary itself. For example:

b         


        
2条回答
  •  礼貌的吻别
    2020-12-21 05:36

    correction - with the right 'data' value your holder works in np.array:

    np.array is definitely not going to work since it expects an iterable, some things like a list of lists, and parses the individual values.

    There is a low level constructor, np.ndarray that takes a buffer parameter. And a np.frombuffer.

    But my impression is that x.__array_interface__['data'][0] is a integer representation of the data buffer location, but not directly a pointer to the buffer. I've only used it to verify that a view shares the same databuffer, not to construct anything from it.

    np.lib.stride_tricks.as_strided uses __array_interface__ for default stride and shape data, but gets the data from an array, not the __array_interface__ dictionary.

    ===========

    An example of ndarray with a .data attribute:

    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': [('', '
    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])
    

    Both of these arrays are views.

    OK, with your holder class, I can make the same thing, using this res.data as the data buffer. Your class creates an object exposing the array interface.

    In [379]: holder=numpy_holder()
    In [380]: buff={'data':res.data, 'shape':(4,3), 'typestr':'

提交回复
热议问题