Skip to content

Commit

Permalink
BUG: Make median work for empty arrays (issue numpy#6462)
Browse files Browse the repository at this point in the history
np.median([]) returns NaN. Fixes bug/regression that raised an IndexError.
Added tests to ensure continued support of empty arrays.
  • Loading branch information
ethankruse authored and jaimefrio committed Mar 15, 2016
1 parent d32c53f commit 7e6959e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion numpy/lib/function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3339,7 +3339,7 @@ def _median(a, axis=None, out=None, overwrite_input=False):
indexer[axis] = slice(index-1, index+1)

# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
if np.issubdtype(a.dtype, np.inexact) and sz > 0:
# warn and return nans like mean would
rout = mean(part[indexer], axis=axis, out=out)
part = np.rollaxis(part, axis, part.ndim)
Expand Down
28 changes: 28 additions & 0 deletions numpy/lib/tests/test_function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2597,6 +2597,34 @@ def test_nan_behavior(self):
assert_equal(np.median(a, (0, 2)), b)
assert_equal(len(w), 1)

def test_empty(self):
# empty arrays
a = np.array([], dtype=float)
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', RuntimeWarning)
assert_equal(np.median(a), np.nan)
assert_(w[0].category is RuntimeWarning)

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

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

# axis 2
b = 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_(w[0].category is RuntimeWarning)

def test_object(self):
o = np.arange(7.)
assert_(type(np.median(o.astype(object))), float)
Expand Down

0 comments on commit 7e6959e

Please sign in to comment.