Subclassing numpy ndarray problem

后端 未结 3 2106
清酒与你
清酒与你 2020-12-06 02:40

I would like to subclass numpy ndarray. However, I cannot change the array. Why self = ... does not change the array? Thanks.

import numpy as np         


        
3条回答
  •  不思量自难忘°
    2020-12-06 02:49

    Perhaps make this a function, rather than a method:

    import numpy as np
    
    def remove_row(arr,col,val):
        return arr[arr[col]!=val]
    
    z = np.array([(1,2,3), (4,5,6), (7,8,9)],
        dtype=[('a', int), ('b', int), ('c', int)])
    
    z=remove_row(z,'a',4)
    print(repr(z))
    
    # array([(1, 2, 3), (7, 8, 9)], 
    #       dtype=[('a', '

    Or, if you want it as a method,

    import numpy as np
    
    class Data(np.ndarray):
    
        def __new__(cls, inputarr):
            obj = np.asarray(inputarr).view(cls)
            return obj
    
        def remove_some(self, col, val):
            return self[self[col] != val]
    
    z = np.array([(1,2,3), (4,5,6), (7,8,9)],
        dtype=[('a', int), ('b', int), ('c', int)])
    d = Data(z)
    d = d.remove_some('a', 4)
    print(d)
    

    The key difference here is that remove_some does not try to modify self, it merely returns a new instance of Data.

提交回复
热议问题