How to return a view of several columns in numpy structured array

后端 未结 5 2146
既然无缘
既然无缘 2021-01-31 18:13

I can see several columns (fields) at once in a numpy structured array by indexing with a list of the field names, for example

import n         


        
5条回答
  •  误落风尘
    2021-01-31 18:25

    I don't think there is an easy way to achieve what you want. In general, you cannot take an arbitrary view into an array. Try the following:

    >>> a
    array([(1.5, 2.5, [[1.0, 2.0], [1.0, 2.0]]),
           (3.0, 4.0, [[4.0, 5.0], [4.0, 5.0]]),
           (1.0, 3.0, [[2.0, 6.0], [2.0, 6.0]])], 
          dtype=[('x', '>> a.view(float)
    array([ 1.5,  2.5,  1. ,  2. ,  1. ,  2. ,  3. ,  4. ,  4. ,  5. ,  4. ,
            5. ,  1. ,  3. ,  2. ,  6. ,  2. ,  6. ])
    

    The float view of your record array shows you how the actual data is stored in memory. A view into this data has to be expressible as a combination of a shape, strides and offset into the above data. So if you wanted, for instance, a view of 'x' and 'y' only, you could do the following:

    >>> from numpy.lib.stride_tricks import as_strided
    >>> b = as_strided(a.view(float), shape=a.shape + (2,),
                       strides=a.strides + a.view(float).strides)
    >>> b
    array([[ 1.5,  2.5],
           [ 3. ,  4. ],
           [ 1. ,  3. ]])
    

    The as_strided does the same as the perhaps easier to understand:

    >>> bb = a.view(float).reshape(a.shape + (-1,))[:, :2]
    >>> bb
    array([[ 1.5,  2.5],
           [ 3. ,  4. ],
           [ 1. ,  3. ]])
    

    Either of this is a view into a:

    >>> b[0,0] =0
    >>> a
    array([(0.0, 2.5, [[0.0, 2.0], [1.0, 2.0]]),
           (3.0, 4.0, [[4.0, 5.0], [4.0, 5.0]]),
           (1.0, 3.0, [[2.0, 6.0], [2.0, 6.0]])], 
          dtype=[('x', '>> bb[2, 1] = 0
    >>> a
    array([(0.0, 2.5, [[0.0, 2.0], [1.0, 2.0]]),
           (3.0, 4.0, [[4.0, 5.0], [4.0, 5.0]]),
           (1.0, 0.0, [[2.0, 6.0], [2.0, 6.0]])], 
          dtype=[('x', '

    It would be nice if either of this could be converted into a record array, but numpy refuses to do so, the reason not being all that clear to me:

    >>> b.view([('x',float), ('y',float)])
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: new type not compatible with array.
    

    Of course what works (sort of) for 'x' and 'y' would not work, for instance, for 'x' and 'value', so in general the answer is: it cannot be done.

提交回复
热议问题