Skip to main content
v2026.11,858 entries · CC-BY 4.0

NumPy NaN: How to Detect, Ignore and Replace np.nan

How to detect, ignore and replace NaN in NumPy, with a worked example showing how nanmean and nan_to_num give different results from the same data.

Written and maintained by CASRAI Editorial Board

Last updated

NaN (Not a Number) is the value NumPy uses for a missing or undefined floating-point result, and it is stored as np.nan. The one thing that matters most for research work: every function that ignores NaN changes the denominator or the total of your statistic, so the choice between np.nanmean, np.nansum and np.nan_to_num changes the number you report. This guide shows the commands from the NumPy manual (v2.5) and a worked example that makes the difference visible.

What NaN is used for in research

The NumPy manual defines np.nan as the “IEEE 754 floating point representation of Not a Number (NaN)”, and notes that NumPy follows the IEEE Standard for Binary Floating-Point for Arithmetic, so NaN is not equivalent to infinity. In research data it appears in two ways: as a placeholder you or an import step put in for a missing measurement, and as the result of an undefined calculation such as np.log(-1), which returns nan.

Because NaN spreads through arithmetic, a single missing value in an array makes mean() return NaN for the whole array. Deciding how to treat it is a data-handling decision that belongs in your analysis plan; see diagnosing missing data (MCAR, MAR, MNAR) before you drop or fill values.

Install or access

NumPy is open-source and documented at numpy.org. Install it from the official instructions on that site, then import it:

import numpy as np

np.nan is a constant in the main namespace, so no extra module is needed.

Step-by-step: create, detect, ignore and replace NaN

  1. Create an array with a missing value. a = np.array([[1, np.nan], [3, 4]])
  2. Detect NaN. np.isnan(a) returns a boolean array that is True where the element is NaN and False elsewhere. For a scalar input it returns a scalar. Count them with np.isnan(a).sum(), which gives 1 here.
  3. Ignore NaN in a statistic. np.nanmean(a) computes the arithmetic mean while ignoring NaNs. It accepts axis, so np.nanmean(a, axis=0) returns [2., 4.] and np.nanmean(a, axis=1) returns [1., 3.5]. np.nansum(a) treats NaN as zero when summing.
  4. Remove NaN elements. Plain boolean indexing keeps only the non-NaN values: a[~np.isnan(a)] returns the flat array [1., 3., 4.]. Note that this flattens a 2-D array.
  5. Replace NaN. np.nan_to_num(a) replaces NaN with zero by default. To choose the replacement, pass nan=, for example np.nan_to_num(a, nan=-9999). By default it also replaces positive and negative infinity with very large finite numbers, and it returns a copy unless you pass copy=False (the in-place operation only occurs if casting to an array does not require a copy).

Output and how to read it

Using the array above, the same data gives three different means depending on the function you choose:

Call Result What it did
a.mean() nan NaN propagates through the whole calculation
np.nanmean(a) 2.6666666666666665 Sum of the non-NaN elements divided by the count of non-NaN elements (8 / 3)
np.nan_to_num(a).mean() 2.0 NaN became 0, so the denominator stayed at 4 (8 / 4)

The NumPy manual’s nanmean notes state that the mean is the sum of the non-NaN elements divided by the number of non-NaN elements. Replacing a missing value with 0 is therefore not neutral: it pulls the mean down from 2.67 to 2.0 in this example. Report which treatment you used and how many values it affected.

NaN versus infinity

NaN and infinity are different values and are handled by different checks. The manual’s isnan examples show np.isnan(np.inf) returning False, and np.isnan([np.log(-1.), 1., np.log(0)]) returning [True, False, False] because np.log(0) is negative infinity, not NaN.

Expression Value np.isnan np.nan_to_num (defaults)
np.log(-1.) nan True 0.0
np.log(0.) -inf False about -1.8e+308 (very large negative finite number)
np.inf inf False about 1.8e+308 (very large finite number)

np.log(-1.) and np.log(0.) also emit runtime warnings when evaluated. np.isfinite is the related check listed beside isnan in the constants page.

Troubleshooting

Why does == np.nan find nothing?

Because NaN is not equal to anything, including itself. np.nan == np.nan is False, and np.array([np.nan]) == np.nan returns [False]. Use np.isnan(x) instead. The same trap appears in data cleaning steps and in data wrangling with missing values.

Why does nansum return 0 and nanmean return NaN for an all-NaN slice?

For an all-NaN slice, np.nanmean returns NaN and raises a RuntimeWarning, while np.nansum returns zero in NumPy versions after 1.9.0. A total of 0 can therefore hide the fact that there was no data at all. Check the count of non-NaN values before reporting a nansum result: (~np.isnan(a)).sum().

Why is my sum nan after nansum?

The manual states that if both positive and negative infinity are present, the sum is NaN. np.nansum([1, np.nan, np.inf]) returns inf, but with both inf and -inf present the result is NaN. Replace or remove the infinities first.

Free alternatives

Tool Function Per its official docs
pandas pandas.isna Detects missing values for an array-like object
pandas DataFrame.dropna Removes missing values (rows by default, axis=0)
pandas DataFrame.fillna Replaces missing values with a specified value
Python standard library math.isnan(x) Returns True if x is a NaN, False otherwise (single numbers, not arrays)

For model-based treatments see multiple imputation: a practical protocol; the SPSS equivalent of this task is covered in handling missing values in SPSS. For selecting elements by condition, see numpy where.

FAQ

How do I check if a value is NaN in NumPy?

Use np.isnan(x). It returns True where x is NaN and False otherwise, and returns a scalar if x is a scalar.

How do I ignore NaN when calculating a mean?

Use np.nanmean(a), optionally with axis. It divides by the number of non-NaN elements.

How do I replace NaN with zero or another value?

Use np.nan_to_num(a) for zero, or np.nan_to_num(a, nan=value) for a value you choose. Be aware that it also converts infinities unless you set posinf and neginf.

Is NaN the same as infinity?

No. NumPy follows IEEE 754, under which NaN is not equivalent to infinity. np.isnan(np.inf) is False.

Sources

NumPy manual (v2.5), checked 2026-10-29:

The example values in the output tables were also reproduced by running the commands on NumPy 2.5.1.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy NaN: How to Detect, Ignore and Replace np.nan

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.