I have an ndarray
subclass, with __array_wrap__
properly implemented, np.apply_along_axis
isn't returning instances of my subclass, but rather ndarrays
. The code below replicates my problem:
import numpy as np
class MySubClass(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array).view(cls)
obj.info = info
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'info', None)
def __array_wrap__(self, out_arr, context=None):
return np.ndarray.__array_wrap__(self, out_arr, context)
sample_ndarray = np.array([[0,5],[2.1,0]])
sample_subclass = MySubClass(sample_ndarray, info="Hi Stack Overflow")
# Find the smallest positive (>0) number along the first axis
min_positive = np.apply_along_axis(lambda x: np.min(np.extract(x>0,x)),
0, sample_subclass)
# No more info
print hasattr(min_positive, 'info')
# Not a subclass
print isinstance(min_positive, MySubClass)
# Is an ndarray
print isinstance(min_positive, np.ndarray)
The most relevant question I could find was this one but the consensus there appears to be that __array_wrap__
needs to be implemented, which I've done. Also, np.extract
and np.min
both return subclasses as expected, it's just when using apply_along_axis
that I see this behavior.
Is there any way to get my code to return my subclass? I am using numpy version 1.11.0