| 3929 | |
| 3930 | |
| 3931 | def _median(a, axis=None, out=None, overwrite_input=False): |
| 3932 | # can't be reasonably be implemented in terms of percentile as we have to |
| 3933 | # call mean to not break astropy |
| 3934 | a = np.asanyarray(a) |
| 3935 | |
| 3936 | # Set the partition indexes |
| 3937 | if axis is None: |
| 3938 | sz = a.size |
| 3939 | else: |
| 3940 | sz = a.shape[axis] |
| 3941 | if sz % 2 == 0: |
| 3942 | szh = sz // 2 |
| 3943 | kth = [szh - 1, szh] |
| 3944 | else: |
| 3945 | kth = [(sz - 1) // 2] |
| 3946 | |
| 3947 | # We have to check for NaNs (as of writing 'M' doesn't actually work). |
| 3948 | supports_nans = np.issubdtype(a.dtype, np.inexact) or a.dtype.kind in 'Mm' |
| 3949 | if supports_nans: |
| 3950 | kth.append(-1) |
| 3951 | |
| 3952 | if overwrite_input: |
| 3953 | if axis is None: |
| 3954 | part = a.ravel() |
| 3955 | part.partition(kth) |
| 3956 | else: |
| 3957 | a.partition(kth, axis=axis) |
| 3958 | part = a |
| 3959 | else: |
| 3960 | part = partition(a, kth, axis=axis) |
| 3961 | |
| 3962 | if part.shape == (): |
| 3963 | # make 0-D arrays work |
| 3964 | return part.item() |
| 3965 | if axis is None: |
| 3966 | axis = 0 |
| 3967 | |
| 3968 | indexer = [slice(None)] * part.ndim |
| 3969 | index = part.shape[axis] // 2 |
| 3970 | if part.shape[axis] % 2 == 1: |
| 3971 | # index with slice to allow mean (below) to work |
| 3972 | indexer[axis] = slice(index, index+1) |
| 3973 | else: |
| 3974 | indexer[axis] = slice(index-1, index+1) |
| 3975 | indexer = tuple(indexer) |
| 3976 | |
| 3977 | # Use mean in both odd and even case to coerce data type, |
| 3978 | # using out array if needed. |
| 3979 | rout = mean(part[indexer], axis=axis, out=out) |
| 3980 | if supports_nans and sz > 0: |
| 3981 | # If nans are possible, warn and replace by nans like mean would. |
| 3982 | rout = np.lib.utils._median_nancheck(part, rout, axis) |
| 3983 | |
| 3984 | return rout |
| 3985 | |
| 3986 | |
| 3987 | def _percentile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, |