Skip to main content

Standard Precipitation (Evapotranspiration) Index

CI PyPI GitHub license

Overview

This is a Python implementation for calculating the Standardized Precipitation Index (SPI) and the Standardized Precipitation Evapotranspiration Index (SPEI) — key indices for identifying droughts. See NCAR's Climate Data Guide for a useful discussion of the relative merits of SPI vs SPEI.

These functions are loosely based on the SPEI package in R by Santiago Beguería and Sergio M. Vicente-Serrano. The paper that most clearly describes the algorithm is:

Lloyd-Hughes, Benjamin, and Mark A. Saunders. "A drought climatology for Europe." International Journal of Climatology 22.13 (2002): 1571-1592.

This paper is included in the docs folder.

Distributions can be fit with either L-moments or Maximum Likelihood Estimation (MLE). L-moments is the recommended method — it is what NCAR's SPI calculators and R's SPI/SPEI packages use, and MLE can be unstable for some distributions and datasets. Indices can be calculated on daily, weekly, monthly, annual or any custom time grouping, at any scale (e.g. 3-month, 6-month), and optionally against a fixed baseline (reference) period.

Requires Python 3.11+.

Installation

pip install standard-precip

or with uv:

uv add standard-precip

Available distributions

Distribution L-moments MLE
Gamma ✔️ ✔️
Exponential ✔️ ✔️
Generalized Extreme Value ✔️ ✔️
Generalized Pareto ✔️ ✔️
Gumbel ✔️ ✔️
Normal ✔️ ✔️
Pearson III ✔️ ✔️
Weibull ✔️ ✔️
Generalized Logistic ✔️ ✔️
Generalized Normal ✔️ ✔️
Kappa ✔️¹ ✔️
Wakeby ✔️ -

¹ Kappa L-moment ratios have no solution for some samples; affected groups yield NaN with a warning.

Note: for the Generalized Logistic, Generalized Normal and Kappa distributions, the L-moments fits use Hosking's distributions (via lmoments3) while the MLE fits use scipy's genlogistic, gennorm and kappa4. These are different parameterizations — parameters from one fit type are not interchangeable with the other.

Basic usage

For a more detailed walkthrough see the example notebook.

import pandas as pd
from standard_precip import SPI
from standard_precip.utils import plot_index

rainfall_data = pd.read_csv("data/monthly_data.csv")

spi = SPI()
df_spi = spi.calculate(
    rainfall_data, "date", "TotalPrecipitation", freq="M", scale=1, fit_type="lmom", dist_type="gam"
)

For a 3-month SPI, set scale=3 (the precipitation is summed over a 3-month rolling window and the result appears in a ..._scale_3_calculated_index column). precip_cols may also be a list of column names to process several series at once.

Plotting:

fig = plot_index(df_spi, "date", "TotalPrecipitation_calculated_index")

Baseline (reference) period

For climate-projection work you typically fit the distributions on a historical baseline and apply them to the full record:

df_spi = spi.calculate(
    rainfall_data,
    "date",
    "TotalPrecipitation",
    baseline_start=1961,
    baseline_end=1990,  # ints = years; dates work too
)

Fitted parameters

return_params=True additionally returns a dataframe of the fitted distribution parameters, one row per (column, frequency group), including the probability of zero precipitation:

df_spi, df_params = spi.calculate(rainfall_data, "date", "TotalPrecipitation", return_params=True)

Annual and custom frequencies

The freq parameter controls the seasonal grouping used for fitting: each day of year (freq="D"), week of year ("W") or month of year ("M") forms its own fitting population. For annual totals there is no seasonal cycle to condition on — use freq=None so that a single distribution is fit to the whole series:

df_annual = df.resample("YE", on="date").sum().reset_index()
df_spi = spi.calculate(df_annual, "date", "TotalPrecipitation", freq=None)

(Do not create a per-year grouping column for annual data: each year would end up alone in its own fitting group.)

For any other custom grouping, add an integer column that assigns each row to a fitting group and pass its name as freq_col.

SPEI

SPEI is calculated exactly like SPI but on the climatic water balance D = P − PET. This package does not compute potential evapotranspiration; supply the water-balance column yourself. Because D takes negative values, use a distribution defined on the whole real line — Vicente-Serrano et al. (2010) recommend the generalized logistic distribution:

from standard_precip import SPEI

df["wb"] = df["precip"] - df["pet"]
df_spei = SPEI().calculate(df, "date", "wb", dist_type="glo", fit_type="lmom")

Gridded data (NetCDF / xarray)

The package operates on one time series at a time, but it composes cleanly with xr.apply_ufunc to compute SPI per grid cell:

import pandas as pd
import xarray as xr
from standard_precip import SPI

ds = xr.open_dataset("precip.nc")
dates = pd.to_datetime(ds["time"].values)


def spi_1d(values, dates):
    df = pd.DataFrame({"date": dates, "p": values})
    out = SPI().calculate(df, "date", "p", freq="M")
    return out["p_calculated_index"].to_numpy()


spi = xr.apply_ufunc(
    spi_1d,
    ds["precip"],
    kwargs={"dates": dates},
    input_core_dims=[["time"]],
    output_core_dims=[["time"]],
    vectorize=True,
)

For large grids, chunk the dataset over the spatial dimensions (never over time) and add dask="parallelized", output_dtypes=[float] to the apply_ufunc call to process cells in parallel. One distribution is fit per cell per frequency group, so expect roughly the single-series cost multiplied by the number of grid cells.

Notes

  1. Although the user is allowed to select the distribution they wish to fit, one should be aware of the support of each distribution. Precipitation data can have zero values (handled for Gamma and Pearson III via the mixed CDF of Thom, 1966) and P − PET can take on negative values. This should be considered when selecting a distribution.
  2. For gamma MLE fits, the location parameter is fixed at 0 unless you pass floc/loc explicitly; unconstrained-loc gamma MLE is ill-posed on precipitation data and produced extreme index values.
  3. L-moment fitting is provided by the lmoments3 package, which is licensed under GPL-3. This package's own code remains Apache-2.0; lmoments3 is an external dependency installed alongside it.

Development

uv sync --group dev
uv run pytest
uv run ruff check .

Contacts

Author - Eric Nussbaumer (ebaumer@gmail.com)

License

Apache License, Version 2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Metadata

Release files for standard-precip 2.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for standard-precip 2.1.0
File Size Uploaded Provenance Actions
standard_precip-2.1.0.tar.gz 369.0 kB Without provenance Details for standard_precip-2.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for standard-precip 2.1.0
File Interpreter ABI Platform Actions
standard_precip-2.1.0-py3-none-any.whl Python 3 none any Details for standard_precip-2.1.0-py3-none-any.whl

Total release size: 392.0 kB

Release files / standard_precip-2.1.0.tar.gz

Download URL standard_precip-2.1.0.tar.gz
Size 369.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8d0e660f9d5113607d79a49a520db949c470577d89167e5f193ab1c75fd9613a
BLAKE2b-256 checksum
How to use checksums
5095eb0881bba43747484847809560cc7c5c62b4b7dd37edefcbf604b86c3390
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / standard_precip-2.1.0-py3-none-any.whl

Download URL standard_precip-2.1.0-py3-none-any.whl
Size 23.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
394d1fff981103c67455fd6e5bdead303b1ddee5264c4f0671b6d21fe8d1f853
BLAKE2b-256 checksum
How to use checksums
0aa0e90b97c352ab9167ec0ab1897aac3f1886068a4a542fce551e52b49a8b2b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for standard-precip 2.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page