MCPcopy Create free account
hub / github.com/numpy/numpy / _median

Function _median

numpy/ma/extras.py:738–820  ·  view source on GitHub ↗
(a, axis=None, out=None, overwrite_input=False)

Source from the content-addressed store, hash-verified

736
737
738def _median(a, axis=None, out=None, overwrite_input=False):
739 # when an unmasked NaN is present return it, so we need to sort the NaN
740 # values behind the mask
741 if np.issubdtype(a.dtype, np.inexact):
742 fill_value = np.inf
743 else:
744 fill_value = None
745 if overwrite_input:
746 if axis is None:
747 asorted = a.ravel()
748 asorted.sort(fill_value=fill_value)
749 else:
750 a.sort(axis=axis, fill_value=fill_value)
751 asorted = a
752 else:
753 asorted = sort(a, axis=axis, fill_value=fill_value)
754
755 if axis is None:
756 axis = 0
757 else:
758 axis = normalize_axis_index(axis, asorted.ndim)
759
760 if asorted.shape[axis] == 0:
761 # for empty axis integer indices fail so use slicing to get same result
762 # as median (which is mean of empty slice = nan)
763 indexer = [slice(None)] * asorted.ndim
764 indexer[axis] = slice(0, 0)
765 indexer = tuple(indexer)
766 return np.ma.mean(asorted[indexer], axis=axis, out=out)
767
768 if asorted.ndim == 1:
769 idx, odd = divmod(count(asorted), 2)
770 mid = asorted[idx + odd - 1:idx + 1]
771 if np.issubdtype(asorted.dtype, np.inexact) and asorted.size > 0:
772 # avoid inf / x = masked
773 s = mid.sum(out=out)
774 if not odd:
775 s = np.true_divide(s, 2., casting='safe', out=out)
776 s = np.lib.utils._median_nancheck(asorted, s, axis)
777 else:
778 s = mid.mean(out=out)
779
780 # if result is masked either the input contained enough
781 # minimum_fill_value so that it would be the median or all values
782 # masked
783 if np.ma.is_masked(s) and not np.all(asorted.mask):
784 return np.ma.minimum_fill_value(asorted)
785 return s
786
787 counts = count(asorted, axis=axis, keepdims=True)
788 h = counts // 2
789
790 # duplicate high if odd number of elements so mean does nothing
791 odd = counts % 2 == 1
792 l = np.where(odd, h, h-1)
793
794 lh = np.concatenate([l,h], axis=axis)
795

Callers

nothing calls this directly

Calls 9

normalize_axis_indexFunction · 0.90
countFunction · 0.85
replace_maskedFunction · 0.85
sortMethod · 0.80
sortFunction · 0.70
ravelMethod · 0.45
meanMethod · 0.45
sumMethod · 0.45
allMethod · 0.45

Tested by

no test coverage detected