Sitemap

Member-only story

Calculating NSE in Python

5 min readSep 21, 2026

--

Press enter or click to view image in full size

Once you understand what Nash-Sutcliffe Efficiency measures, implementing it is genuinely a few lines of code. But those few lines have a handful of sharp edges — NaNs, misaligned series, zero-variance observations — that will silently give you wrong numbers if you’re not careful. This article builds the implementation up from the formula, then walks through the bugs I’ve actually hit while doing this in practice.

The minimal NumPy implementation

Starting from the formula NSE = 1 - sum((obs - sim)^2) / sum((obs - obs_mean)^2), the direct NumPy translation is:

import numpy as np
def nse(obs: np.ndarray, sim: np.ndarray) -> float:
obs = np.asarray(obs, dtype=float)
sim = np.asarray(sim, dtype=float)
numerator = np.sum((obs - sim) ** 2)
denominator = np.sum((obs - obs.mean()) ** 2)
return 1.0 - numerator / denominator

Line by line: the first two lines coerce both inputs to float NumPy arrays, which matters because if you accidentally pass integer arrays, intermediate subtraction and squaring still works fine, but it protects you against accidentally passing in, say, a list of Decimal objects or an object-dtype array from a badly parsed CSV column. numerator is the sum of squared differences between observed…

--

--

Andy Taylor
Andy Taylor

Written by Andy Taylor

Data scientist writing about rainfall–runoff ML and scientific Python. HEMA instructor and researcher, and author of several books on early fencing sources.