How to replace infinite values before aggregation in NumPy (with Code)
The Short Answer (TL;DR)
Set both positive and negative infinity to NaN with explicit posinf and neginf arguments, retain existing NaNs, and aggregate only finite observations. Record the excluded counts and leave a mean undefined when a column has no finite observations.
import numpy as np
x = np.array([2.,np.inf,6.,-np.inf,np.nan])
print(np.nanmean(np.nan_to_num(x,nan=np.nan,posinf=np.nan,neginf=np.nan)))
Detailed Implementation
This example uses synthetic data and does not need a network connection. Install the recorded package versions in a separate Python environment before running it.
python -m pip install numpy==2.5.4
from pathlib import Path
import numpy as np
def finite_column_report(values):
raw=np.asarray(values)
if raw.ndim!=2 or raw.shape[1]==0 or raw.dtype.kind not in "iuf":
raise ValueError("Require a real numeric matrix with at least one column.")
x=raw.astype(np.float64,copy=False)
if np.any(np.abs(x[np.isfinite(x)])>1e12):
raise ValueError("Finite measurements must have magnitude at most 1e12.")
# Capture the original reasons before converting infinities to missing values.
positive_infinity=np.isposinf(x)
negative_infinity=np.isneginf(x)
originally_missing=np.isnan(x)
cleaned=np.nan_to_num(x,copy=True,nan=np.nan,posinf=np.nan,neginf=np.nan)
finite=np.isfinite(cleaned)
counts=finite.sum(axis=0,dtype=np.int64)
totals=np.where(finite,cleaned,0.0).sum(axis=0,dtype=np.float64)
means=np.full(x.shape[1],np.nan,dtype=np.float64)
np.divide(totals,counts,out=means,where=counts>0)
audit={"input_rows":x.shape[0],"finite_counts":counts,
"positive_infinity_counts":positive_infinity.sum(axis=0),
"negative_infinity_counts":negative_infinity.sum(axis=0),
"original_missing_counts":originally_missing.sum(axis=0),
"infinite_positions":np.argwhere(positive_infinity|negative_infinity)}
return cleaned,means,audit
# Rows are synthetic observations; each column has its own measurement units.
data=np.array([[2.,np.inf,4.,np.nan],[np.inf,6.,np.nan,np.inf],
[8.,-np.inf,10.,-np.inf],[np.nan,12.,16.,np.nan]])
cleaned,means,audit=finite_column_report(data)
text=("CLEANED COPY\n"+np.array2string(cleaned)+"\nFINITE-OBSERVATION MEANS\n"+
np.array2string(means)+"\n"+"\n".join(f"{k}={v}" for k,v in audit.items())+"\n")
Path("finite-column-aggregation.txt").write_text(text,encoding="utf-8")
print(text)
The finite-observation means are [5, 9, 10, NaN]. Counts are [2, 2, 3, 0], and the all-nonfinite fourth column remains undefined. The cleaned copy contains no infinities; the source and the original missing/infinity audit remain available.
Why must both infinity replacements be explicit?
The nan_to_num defaults replace infinities with extreme finite values and replace NaN with zero. Those are computational defaults, not a measurement policy. An extreme replacement can dominate a mean or overflow a later sum. Passing nan=np.nan, posinf=np.nan and neginf=np.nan makes this example exclude all three nonfinite cases while retaining their original reasons in the audit. A justified finite replacement requires a separate rule based on the data source.
Why keep the original missing and infinite counts?
After conversion, an original NaN and either sign of infinity all appear as NaN. The separate masks preserve that distinction before it is lost. In the four-row fixture, finite counts are [2, 2, 3, 0], positive-infinity counts [1, 1, 0, 1], negative-infinity counts [0, 1, 0, 1] and original-missing counts [1, 0, 1, 2]. These counts sum to four within each column. The recorded row-column positions identify every original infinity.
Which denominator defines the reported mean?
Each column uses its own finite observation count. The first column averages two and eight to five; the second averages six and twelve to nine. The third averages four, ten and sixteen to ten. Dividing these sums by all four input rows would silently treat excluded entries as zero contributions and answer a different question. This example excludes cells within each column rather than removing every row that contains a nonfinite cell.
What happens when a column is entirely nonfinite?
The fourth column has zero finite observations. Its mean remains NaN because division is applied only where the count is positive. The short answer uses nanmean on a vector that has finite data; an all-NaN slice passed to nanmean instead returns NaN and emits a RuntimeWarning. The full example avoids that expected warning by explicitly constructing the count and denominator, without globally suppressing warnings or inventing a zero mean.
Does the conversion change the source array?
The helper requests copy=True and returns a separate cleaned array. A read-only input also works, and validation confirms that the original nonfinite values remain in the source. The independent reference uses Python math.isfinite and math.fsum on each original column. Reordering rows preserves the result for this fixture. Empty input with a known positive column count returns missing means and zero observed counts, retaining the requested output layout.
When is exclusion the wrong policy?
Infinity may signal overflow, division by zero, an unbounded ratio or a meaningful limit in a mathematical calculation. Investigate the reason before replacing it in measured data. Exclusion does not recover the missing measurement or make a mean representative when failure depends on the underlying value. The helper accepts only real numeric matrices, accumulates in float64 and bounds finite magnitudes at one trillion. Large totals or precision-sensitive applications still need a numerical and domain review. Complex, Boolean and string data require a different contract.
Mathematical Context
For column j, let F_j contain row indices with finite original measurements. The reported mean is the sum of x_ij over F_j divided by the size of F_j, when that size is positive. It is undefined here when the count is zero. Each column keeps its own measurement units, while counts are dimensionless. In the example, two plus eight divided by two is five. This is a descriptive mean of the retained measurements; it is not an unbiasedness claim about a population with missing or invalid observations.
\[ \bar{x}_j=\frac{\sum_{i\in F_j}x_{ij}}{|F_j|},\qquad F_j=\{i:x_{ij}\ \mathrm{is\ finite}\},\quad |F_j|>0 \]
Reproducibility
Executed with Python 3.12.14; numpy 2.5.4. Automated checks confirm the stated output properties.
Primary documentation
- NumPy nan_to_num: explicit NaN and infinity replacements
- NumPy isfinite: finite-value masks
- NumPy nanmean: denominators and all-NaN slices