Skip to content

Commit

Permalink
Merge pull request numpy#8705 from juliantaylor/ma-median-empty
Browse files Browse the repository at this point in the history
BUG: fix ma.median for empty ndarrays
  • Loading branch information
eric-wieser authored Feb 27, 2017
2 parents 533cef9 + 05aa44d commit 2dd9125
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
7 changes: 7 additions & 0 deletions numpy/ma/extras.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,13 @@ def _median(a, axis=None, out=None, overwrite_input=False):
else:
axis = normalize_axis_index(axis, asorted.ndim)

if asorted.shape[axis] == 0:
# for empty axis integer indices fail so use slicing to get same result
# as median (which is mean of empty slice = nan)
indexer = [slice(None)] * asorted.ndim
indexer[axis] = slice(0, 0)
return np.ma.mean(asorted[indexer], axis=axis, out=out)

if asorted.ndim == 1:
counts = count(asorted)
idx, odd = divmod(count(asorted), 2)
Expand Down
6 changes: 3 additions & 3 deletions numpy/ma/tests/test_extras.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,14 +1039,14 @@ def test_empty(self):

# axis 0 and 1
b = np.ma.masked_array(np.array([], dtype=float, ndmin=2))
assert_equal(np.median(a, axis=0), b)
assert_equal(np.median(a, axis=1), b)
assert_equal(np.ma.median(a, axis=0), b)
assert_equal(np.ma.median(a, axis=1), b)

# axis 2
b = np.ma.masked_array(np.array(np.nan, dtype=float, ndmin=2))
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', RuntimeWarning)
assert_equal(np.median(a, axis=2), b)
assert_equal(np.ma.median(a, axis=2), b)
assert_(w[0].category is RuntimeWarning)

def test_object(self):
Expand Down

0 comments on commit 2dd9125

Please sign in to comment.