NumPy RuntimeWarning: mean of empty slice, overflow, divide by zero (tested)

NumPy emits RuntimeWarning and returns nan/inf for an empty mean, an all-NaN slice, overflow in exp, divide by zero and invalid values. np.errstate silences the floating-point ones but not "Mean of empty slice". Every block below was run on NumPy 2.5.4.

1. The six common warnings

import warnings
import numpy as np
warnings.simplefilter("always")   # show every warning, not just the first per line

print(np.mean(np.array([])))                    # empty array
print(np.nanmean(np.array([np.nan, np.nan])))   # all-NaN
print(np.nanmax(np.array([np.nan, np.nan])))    # all-NaN
print(np.exp(np.array([1000.0])))               # too big for float64
print(np.array([1.0, 0.0]) / np.array([0.0, 0.0]))  # x/0 and 0/0
print(np.log(np.array([0.0, -1.0])))            # log(0), log(-1)

Output:

/usr/local/lib/python3.14/site-packages/numpy/_core/fromnumeric.py:3862: RuntimeWarning: Mean of empty slice
  return _methods._mean(a, axis=axis, dtype=dtype,
/usr/local/lib/python3.14/site-packages/numpy/_core/_methods.py:142: RuntimeWarning: invalid value encountered in scalar divide
  ret = ret.dtype.type(ret / rcount)
/w/b1.py:6: RuntimeWarning: Mean of empty slice
  print(np.nanmean(np.array([np.nan, np.nan])))   # all-NaN
/w/b1.py:7: RuntimeWarning: All-NaN slice encountered
  print(np.nanmax(np.array([np.nan, np.nan])))    # all-NaN
/w/b1.py:8: RuntimeWarning: overflow encountered in exp
  print(np.exp(np.array([1000.0])))               # too big for float64
/w/b1.py:9: RuntimeWarning: divide by zero encountered in divide
  print(np.array([1.0, 0.0]) / np.array([0.0, 0.0]))  # x/0 and 0/0
/w/b1.py:9: RuntimeWarning: invalid value encountered in divide
  print(np.array([1.0, 0.0]) / np.array([0.0, 0.0]))  # x/0 and 0/0
/w/b1.py:10: RuntimeWarning: divide by zero encountered in log
  print(np.log(np.array([0.0, -1.0])))            # log(0), log(-1)
/w/b1.py:10: RuntimeWarning: invalid value encountered in log
  print(np.log(np.array([0.0, -1.0])))            # log(0), log(-1)
nan
nan
nan
[inf]
[inf nan]
[-inf  nan]

None of these stop your program: NumPy returns nan, inf or -inf and warns. np.mean of an empty array emits two warnings ("Mean of empty slice" plus "invalid value encountered in scalar divide", from 0/0 inside NumPy). nanmean of an all-NaN array also says "Mean of empty slice"; nanmax/nanmin say "All-NaN slice encountered". The block calls warnings.simplefilter("always") because Python's default filter shows each warning only once per source line, which can make a warning appear to vanish on the second run of a loop.

2. np.errstate does not silence all of them

import warnings
import numpy as np
warnings.simplefilter("always")

with np.errstate(all="ignore"):
    print("exp:", np.exp(np.array([1000.0])))
    print("div:", np.array([1.0, 0.0]) / 0.0)
    print("mean:", np.mean(np.array([])))
    print("nanmean:", np.nanmean(np.array([np.nan])))

Output:

/usr/local/lib/python3.14/site-packages/numpy/_core/fromnumeric.py:3862: RuntimeWarning: Mean of empty slice
  return _methods._mean(a, axis=axis, dtype=dtype,
/w/b2.py:9: RuntimeWarning: Mean of empty slice
  print("nanmean:", np.nanmean(np.array([np.nan])))
exp: [inf]
div: [inf nan]
mean: nan
nanmean: nan

np.errstate controls floating-point errors (overflow, divide by zero, invalid value, underflow), so the exp and division warnings disappear. "Mean of empty slice" is a regular Python warnings.warn call inside NumPy, so it still prints, both for mean and nanmean.

3. Suppress a specific warning (scoped)

import warnings
import numpy as np

with warnings.catch_warnings():
    warnings.filterwarnings("ignore", message="Mean of empty slice")
    warnings.filterwarnings("ignore", message="All-NaN slice encountered")
    with np.errstate(invalid="ignore"):
        print(np.mean(np.array([])), np.nanmax(np.array([np.nan])))

# after the with-block the filters are restored
warnings.simplefilter("always")
print(np.mean(np.array([])))

Output:

/usr/local/lib/python3.14/site-packages/numpy/_core/fromnumeric.py:3862: RuntimeWarning: Mean of empty slice
  return _methods._mean(a, axis=axis, dtype=dtype,
/usr/local/lib/python3.14/site-packages/numpy/_core/_methods.py:142: RuntimeWarning: invalid value encountered in scalar divide
  ret = ret.dtype.type(ret / rcount)
nan nan
nan

Combine warnings.catch_warnings() with a message= filter (a regex matched against the start of the message) for the Python-level warnings, and np.errstate for the floating-point ones. Both are restored when the with block ends, as the last line shows. Prefer this to a global warnings.filterwarnings("ignore"), which also hides warnings you would want to see.

4. Turn warnings into errors to find the line

import warnings
import numpy as np

np.seterr(all="raise")
try:
    np.exp(np.array([1000.0]))
except FloatingPointError as e:
    print("FloatingPointError:", e)

try:
    np.mean(np.array([]))
except FloatingPointError as e:
    print("FloatingPointError:", e)

Output:

/usr/local/lib/python3.14/site-packages/numpy/_core/fromnumeric.py:3862: RuntimeWarning: Mean of empty slice
  return _methods._mean(a, axis=axis, dtype=dtype,
FloatingPointError: overflow encountered in exp
FloatingPointError: invalid value encountered in scalar divide

np.seterr(all="raise") turns floating-point problems into FloatingPointError with a traceback pointing at your line. It does not affect "Mean of empty slice", which still prints as a warning before the 0/0 raises.

import warnings
import numpy as np
warnings.filterwarnings("error", category=RuntimeWarning)

try:
    np.mean(np.array([]))
except RuntimeWarning as e:
    print("caught:", e)

try:
    np.exp(np.array([1000.0]))
except RuntimeWarning as e:
    print("caught:", e)

Output:

caught: Mean of empty slice
caught: overflow encountered in exp

warnings.filterwarnings("error", category=RuntimeWarning) turns every RuntimeWarning, including "Mean of empty slice", into an exception you can catch with except RuntimeWarning. Run your script with python -W error::RuntimeWarning script.py for the same effect without editing code.

5. Fix the cause instead

import warnings
import numpy as np
warnings.simplefilter("always")

a = np.array([])
print(a.mean() if a.size else np.nan)            # check size first

num = np.array([1.0, 0.0, 6.0])
den = np.array([0.0, 0.0, 3.0])
print(np.divide(num, den, out=np.full_like(num, np.nan), where=den != 0))

x = np.array([-1000.0, 0.0, 1000.0])
print(1 / (1 + np.exp(-np.clip(x, -500, 500))))  # stable sigmoid

v = np.array([0.0, 2.0])
print(np.log(v, out=np.full_like(v, -np.inf), where=v > 0))
print(np.log1p(np.array([1e-20])), np.log(1 + 1e-20))

Output:

nan
[nan nan  2.]
[7.12457641e-218 5.00000000e-001 1.00000000e+000]
[      -inf 0.69314718]
[1.e-20] 0.0

Check .size before averaging; use np.divide(..., where=den != 0) with an out array so zero denominators get a value you choose; clip the input to exp (here a sigmoid) so it cannot overflow; and use where= for log. np.log1p(x) is accurate for tiny x where np.log(1 + x) rounds to 0.

Related: numpy has no attribute 'int' / 'float' · suppress pandas warnings · OverflowError: math range error.

Frequently asked questions

How do I suppress 'RuntimeWarning: Mean of empty slice'?

It is a Python warning, not a floating-point error, so np.errstate does not hide it. Use warnings.catch_warnings() with warnings.filterwarnings('ignore', message='Mean of empty slice'), or check a.size before calling mean.

How do I fix 'overflow encountered in exp'?

The input is too large for float64 (exp(710) already overflows). Clip the input, for example np.exp(np.clip(x, -500, 500)), or rewrite the formula in a stable form.

How do I find which line causes a NumPy RuntimeWarning?

Call np.seterr(all='raise') for floating-point errors, or warnings.filterwarnings('error', category=RuntimeWarning) for all RuntimeWarnings, so the warning becomes an exception with a traceback.

Written with AI assistance. Measured on 2026-10-23 in Docker: python:3-alpine (Python 3.14.7) with numpy 2.5.4. Each block was run verbatim and the output pasted unedited. PlainTables is our extension; Python and NumPy are free.