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

后端 未结 5 2149
既然无缘
既然无缘 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:29

    In my case 'several columns' happens to be equal to two columns of the same data type, where I can use the following function to make a view:

    def make_view(arr, fields, dtype):
        offsets = [arr.dtype.fields[f][1] for f in fields]
        offset = min(offsets)
        stride = max(offsets)
        return np.ndarray((len(arr), 2), buffer=arr, offset=offset, strides=(arr.strides[0], stride-offset), dtype=dtype)
    

    I think this boils down the the same thing @Jamie said, it cannot be done in general, but for two columns of the same dtype it can. The result of this function is not a dict but a good old fashioned numpy array.

提交回复
热议问题