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

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

    You can create a dtype object contains only the fields that you want, and use numpy.ndarray() to create a view of original array:

    import numpy as np
    strc = np.zeros(3, dtype=[('x', int), ('y', float), ('z', int), ('t', "i8")])
    
    def fields_view(arr, fields):
        dtype2 = np.dtype({name:arr.dtype.fields[name] for name in fields})
        return np.ndarray(arr.shape, dtype2, arr, 0, arr.strides)
    
    v1 = fields_view(strc, ["x", "z"])
    v1[0] = 10, 100
    
    v2 = fields_view(strc, ["y", "z"])
    v2[1:] = [(3.14, 7)]
    
    v3 = fields_view(strc, ["x", "t"])
    
    v3[1:] = [(1000, 2**16)]
    
    print(strc)
    

    here is the output:

    [(10, 0.0, 100, 0L) (1000, 3.14, 7, 65536L) (1000, 3.14, 7, 65536L)]
    

提交回复
热议问题