yes as mentioned in one the comments one could use an umasked sort here instead of using the ma module as nans sort to the end, would probably be faster and need more memory. For that we probably need a masked_median function which takes a data, a mask array and a sort function but is not specific to MaskedArray. Then use this for both nanmedian and ma. I ran out of time to do this refactoring but I could maybe still squeeze it in somehow if you wish.