1

I'm trying to subclass an ndarray so that I can add some additional fields. When I do this however, I get odd behavior in a variety of numpy functions. For example nanmin returns now return an object of the type of my new array classs, whereas previously I'd get a float64. Why? Is this a bug with nanmin or my class?

import numpy as np

class NDArrayWithColumns(np.ndarray):
    def __new__(cls, obj, columns=None):
        obj = obj.view(cls)
        obj.columns = tuple(columns)
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.columns = getattr(obj, 'columns', None)

NAN = float("nan")
r = np.array([1.,0.,1.,0.,1.,0.,1.,0.,NAN, 1., 1.])
print "MIN", np.nanmin(r), type(np.nanmin(r)) 

gives:

MIN 0.0 <type 'numpy.float64'>

but

>>> r = NDArrayWithColumns(r, ["a"])
>>> print "MIN", np.nanmin(r), type(np.nanmin(r))
MIN 0.0 <class '__main__.NDArrayWithColumns'>
>>> print r.shape 
(11,)

Note the change in type, and also that str(np.nanmin(r)) shows 1 field, not 11.

In case you're interested, I'm subclassing because I'd like to track columns names is matrices of a single type but structure arrays and record type arrays allow for varying type).

1 Answer 1

1

You need to implement the __array_wrap__ method that gets called at the end of ufuncs, per the docs:

    def __array_wrap__(self, out_arr, context=None):
        print('In __array_wrap__:')
        print('   self is %s' % repr(self))
        print('   arr is %s' % repr(out_arr))
        # then just call the parent
        return np.ndarray.__array_wrap__(self, out_arr, context)
Sign up to request clarification or add additional context in comments.

1 Comment

I'm sure not it helps. Your code doesn't change the final behavior and it not clear what decision logic might go in here to fix it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.