# Python statistics libraries

Python statistics libraries compute descriptive statistics, run hypothesis tests, and fit statistical models to data. Some libraries specialize in one family of models, such as survival analysis, Bayesian inference, or time series forecasting. These libraries let analysts, researchers, and AI agents test hypotheses and fit models in Python.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [SciPy](#scipy) | 389.6M | 15.2K | Aug 2026 | BSD-3-Clause |
| [statsmodels](#statsmodels) | 40.4M | 11.8K | Aug 2026 | BSD-3-Clause |
| [CmdStanPy](#cmdstanpy) | 4.3M | 198 | Nov 2026 | BSD-3-Clause |
| [Prophet](#prophet) | 4.1M | 20.5K | Oct 2026 | MIT |
| [ArviZ](#arviz) | 2.7M | 1.9K | Aug 2026 | Apache-2.0 |
| [lifelines](#lifelines) | 2.2M | 2.6K | Mar 2026 | MIT |
| [StatsForecast](#statsforecast) | 1.8M | 5.0K | Jul 2026 | Apache-2.0 |
| [pmdarima](#pmdarima) | 1.7M | 1.7K | Nov 2025 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[SciPy](#scipy) has the most monthly downloads in this comparison, at 389.6M, a count that covers all its scientific computing.

## Capabilities

| Library | NUTS sampler | Cox PH regression | Forecasting API |
| --- | --- | --- | --- |
| [SciPy](#scipy) | No | No | No |
| [statsmodels](#statsmodels) | No | Yes | Yes |
| [CmdStanPy](#cmdstanpy) | Yes | No | No |
| [Prophet](#prophet) | Yes | No | Yes |
| [ArviZ](#arviz) | No | No | No |
| [lifelines](#lifelines) | No | Yes | No |
| [StatsForecast](#statsforecast) | No | No | Yes |
| [pmdarima](#pmdarima) | No | No | Yes |

## Libraries

### SciPy

[GitHub](https://github.com/scipy/scipy) · [PyPI](https://pypi.org/project/scipy) · [Docs](https://docs.scipy.org/doc/scipy/)

Provides statistical tests, probability distributions, and numerical routines.

- Downloads / mo: 389.6M
- Stars: 15.2K
- Last release: 1.18.1
- License: BSD-3-Clause
- Capabilities: [From the SciPy docs](https://docs.scipy.org/doc/scipy/)

**Strengths**

- **Covers tests and distributions.** Use distributions, correlations, and hypothesis tests from the same package.
- **Controls false discovery rates.** Adjust p-values with false_discovery_control().

**Watch out for**

- **ttest_ind assumes equal variances.** Set equal_var=False to compare groups with unequal variances.
- **Missing values propagate by default.** Choose a nan_policy when inputs contain missing values.

```sh
pip install scipy
```

**mwaskom/seaborn** (14.1K stars)

[mwaskom/seaborn](https://github.com/mwaskom/seaborn) 

```python
def _fit(self, fit_data, weights=None):
    """Fit the scipy kde while adding bw_adjust logic and version check."""
    fit_kws = {"bw_method": self.bw_method}
    if weights is not None:
        fit_kws["weights"] = weights

    kde = gaussian_kde(fit_data, **fit_kws)
    kde.set_bandwidth(kde.factor * self.bw_adjust)

    return kde

```

[seaborn/_statistics.py](https://github.com/mwaskom/seaborn/blob/c1cb287835852406691aed60ea0c62710f2c6b18/seaborn/_statistics.py#L137-L146) · [More projects using SciPy →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20scipy%20to%20fit%20statistical%20models%2C%20compare%20groups%20and%20generate%20predictions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import numpy as np
from scipy import stats
rng = np.random.default_rng()
rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
stats.ttest_ind(rvs1, rvs2)

```

From [scipy.stats.ttest_ind.html](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html)

### statsmodels

[GitHub](https://github.com/statsmodels/statsmodels) · [PyPI](https://pypi.org/project/statsmodels) · [Docs](https://www.statsmodels.org/stable/)

Estimates statistical models and runs hypothesis tests.

- Downloads / mo: 40.4M
- Stars: 11.8K
- Last release: 0.15.0
- License: BSD-3-Clause
- Capabilities: [From the statsmodels docs](https://www.statsmodels.org/stable/)

**Strengths**

- **Accepts R-style model formulas.** Describe models with formulas against pandas DataFrames.
- **Fits Bayesian mixed-effects models.** Estimate binomial and Poisson mixed models with Bayesian approximation methods.

**Watch out for**

- **Missing data needs explicit handling.** Set missing='raise' or clean missing values before fitting.
- **Array OLS omits automatic intercepts.** Call add_constant when the model needs an intercept.

```sh
pip install statsmodels
```

**mwaskom/seaborn** (14.1K stars)

[mwaskom/seaborn](https://github.com/mwaskom/seaborn) 

```python
def fit_statsmodels(self, grid, model, **kwargs):
    """More general regression function using statsmodels objects."""
    import statsmodels.tools.sm_exceptions as sme
    X, y = np.c_[np.ones(len(self.x)), self.x], self.y
    grid = np.c_[np.ones(len(grid)), grid]

    def reg_func(_x, _y):
        err_classes = (sme.PerfectSeparationError,)
        try:
            with warnings.catch_warnings():
                if hasattr(sme, "PerfectSeparationWarning"):
                    # statsmodels>=0.14.0
                    warnings.simplefilter("error", sme.PerfectSeparationWarning)
                    err_classes = (*err_classes, sme.PerfectSeparationWarning)
                yhat = model(_y, _x, **kwargs).fit().predict(grid)
        except err_classes:
            yhat = np.empty(len(grid))
            yhat.fill(np.nan)
        return yhat

    yhat = reg_func(X, y)
    if self.ci is None:
        return yhat, None

    yhat_boots = algo.bootstrap(X, y,
                                func=reg_func,
                                n_boot=self.n_boot,
                                units=self.units,
                                seed=self.seed)
    return yhat, yhat_boots

```

[seaborn/regression.py](https://github.com/mwaskom/seaborn/blob/c1cb287835852406691aed60ea0c62710f2c6b18/seaborn/regression.py#L275-L304) · [More projects using statsmodels →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20statsmodels%20to%20fit%20statistical%20models%2C%20compare%20groups%20and%20generate%20predictions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
# Load data
dat = sm.datasets.get_rdataset("Guerry", "HistData").data
# Fit regression model (using the natural log of one of the regressors)
results = smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data=dat).fit()
# Inspect the results
print(results.summary())

```

From [index.html](https://www.statsmodels.org/stable/index.html)

### CmdStanPy

[GitHub](https://github.com/stan-dev/cmdstanpy) · [PyPI](https://pypi.org/project/cmdstanpy) · [Docs](https://mc-stan.org/cmdstanpy/)

Provides a Python interface to CmdStan.

- Downloads / mo: 4.3M
- Stars: 198
- Last release: 1.3.2
- License: BSD-3-Clause
- Capabilities: [From the CmdStanPy docs](https://mc-stan.org/cmdstanpy/)

```sh
pip install cmdstanpy
```

**meta/prophet** (20.5K stars)

[meta/prophet](https://github.com/meta/prophet) 

```python
def sampling(
    self,
    stan_init: dict[str, float],
    stan_data: dict[str, Any],
    samples: int,
    **kwargs: Any,
) -> OrderedDict[str, np.ndarray]:
    if 'inits' not in kwargs and 'init' in kwargs:
        stan_init = self.sanitize_custom_inits(stan_init, kwargs['init'])
        del kwargs['init']

    inits_list, data_list = self.prepare_data(stan_init, stan_data)
    args = dict(
        data=data_list,
        inits=inits_list,
    )
    if 'chains' not in kwargs:
        kwargs['chains'] = 4
    iter_half = samples // 2
    kwargs['iter_sampling'] = iter_half
    if 'iter_warmup' not in kwargs:
        kwargs['iter_warmup'] = iter_half
    args.update(kwargs)

    self.stan_fit = self.model.sample(**args)
    res = self.stan_fit.draws()
    (samples, c, columns) = res.shape
    res = res.reshape((samples * c, columns))
    params = self.stan_to_dict_numpy(self.stan_fit.column_names, res)

    for par in params:
        s = params[par].shape
        if s[1] == 1:
            params[par] = params[par].reshape((s[0],))

        if par in ['delta', 'beta'] and len(s) < 2:
            params[par] = params[par].reshape((-1, 1))

    return params

```

[python/prophet/models.py](https://github.com/meta/prophet/blob/5cf15c0f6e5d5259d9dd8d511fb4e15a45884cdc/python/prophet/models.py#L186-L224) · [More projects using CmdStanPy →](https://dashboard.exa.ai/playground/search?q=cmdstanpy%20GitHub%20projects)

**Quickstart**

```python
import os
from cmdstanpy import cmdstan_path, CmdStanModel

# specify locations of Stan program file and data
stan_file = os.path.join(cmdstan_path(), 'examples', 'bernoulli', 'bernoulli.stan')
data_file = os.path.join(cmdstan_path(), 'examples', 'bernoulli', 'bernoulli.data.json')

# instantiate a model; compiles the Stan program by default
model = CmdStanModel(stan_file=stan_file)

# obtain a posterior sample from the model conditioned on the data
fit = model.sample(chains=4, data=data_file)

```

From [README.md](https://github.com/stan-dev/cmdstanpy/blob/develop/README.md)

### Prophet

[GitHub](https://github.com/meta/prophet) · [PyPI](https://pypi.org/project/prophet) · [Docs](https://facebook.github.io/prophet/)

Runs an automatic forecasting procedure.

- Downloads / mo: 4.1M
- Stars: 20.5K
- Last release: 1.5.0
- License: MIT
- Capabilities: [From the Prophet docs](https://facebook.github.io/prophet/)

```sh
pip install prophet
```

**apache/superset** (75.5K stars)

[apache/superset](https://github.com/apache/superset) 

```python
def _prophet_fit_and_predict(  # pylint: disable=too-many-arguments
    df: DataFrame,
    confidence_interval: float,
    yearly_seasonality: Union[bool, str, int],
    weekly_seasonality: Union[bool, str, int],
    daily_seasonality: Union[bool, str, int],
    periods: int,
    freq: str,
) -> DataFrame:
    """
    Fit a prophet model and return a DataFrame with predicted results.
    """
    try:
        # `prophet` complains about `plotly` not being installed
        with suppress_logging("prophet.plot"):
            # pylint: disable=import-outside-toplevel
            from prophet import Prophet

        prophet_logger = logging.getLogger("prophet.plot")
        prophet_logger.setLevel(logging.CRITICAL)
        prophet_logger.setLevel(logging.NOTSET)
    except ModuleNotFoundError as ex:
        raise InvalidPostProcessingError(_("`prophet` package not installed")) from ex
    model = Prophet(
        interval_width=confidence_interval,
        yearly_seasonality=yearly_seasonality,
        weekly_seasonality=weekly_seasonality,
        daily_seasonality=daily_seasonality,
    )
    if df["ds"].dt.tz:
        df["ds"] = df["ds"].dt.tz_convert(None)
    try:
        model.fit(df)
        future = model.make_future_dataframe(periods=periods, freq=freq)
        forecast = model.predict(future)[["ds", "yhat", "yhat_lower", "yhat_upper"]]
    except Exception as ex:  # noqa: BLE001
        raise InvalidPostProcessingError(
            _(
                "Unable to generate forecast: %(error)s",
                error=str(ex),
            )
        ) from ex
    return forecast.join(df.set_index("ds"), on="ds").set_index(["ds"])

```

[superset/utils/pandas_postprocessing/prophet.py](https://github.com/apache/superset/blob/18430a95f7da90dd848bc4ed988db58dd8c3362d/superset/utils/pandas_postprocessing/prophet.py#L43-L85) · [More projects using Prophet →](https://dashboard.exa.ai/playground/search?q=prophet%20GitHub%20projects)

**Quickstart**

```python
# Python
import pandas as pd
from prophet import Prophet

# Python
df = pd.read_csv('https://raw.githubusercontent.com/facebook/prophet/main/examples/example_wp_log_peyton_manning.csv')
df.head()

# Python
m = Prophet()
m.fit(df)

```

From [quick_start.html](https://github.com/meta/prophet/blob/f57c4e13a29d18f927f2516f04990a3540711694/docs/_docs/quick_start.md)

### ArviZ

[GitHub](https://github.com/arviz-devs/arviz) · [PyPI](https://pypi.org/project/arviz) · [Docs](https://python.arviz.org/)

Exposes ArviZ features in one namespace.

- Downloads / mo: 2.7M
- Stars: 1.9K
- Last release: 1.3.0
- License: Apache-2.0
- Capabilities: [From the ArviZ docs](https://python.arviz.org/)

```sh
pip install arviz
```

**pymc-labs/pymc-marketing** (1.3K stars)

[pymc-labs/pymc-marketing](https://github.com/pymc-labs/pymc-marketing) 

```python
def _create_get_hdi_plot_data(hdi_kwargs) -> GetPlotData:
    def get_plot_data(data: xr.DataArray) -> xr.DataArray:
        hdi = az.hdi(data, **hdi_kwargs)
        if isinstance(hdi, xr.Dataset) and data.name is not None:
            return hdi[data.name]
        return hdi  # DataArray case

    return get_plot_data

```

[pymc_marketing/plot.py](https://github.com/pymc-labs/pymc-marketing/blob/93a9bd1626c777285463a535c43ec9c94f672359/pymc_marketing/plot.py#L266-L273) · [More projects using ArviZ →](https://dashboard.exa.ai/playground/search?q=arviz%20GitHub%20projects)

**Quickstart**

```python
import arviz as az
import numpy as np

data = np.random.default_rng().normal(size=2000)
az.hdi(data, 0.68)

```

From [visualization.py](https://github.com/arviz-devs/arviz-stats/blob/main/src/arviz_stats/visualization.py)

### lifelines

[GitHub](https://github.com/CamDavidsonPilon/lifelines) · [PyPI](https://pypi.org/project/lifelines) · [Docs](https://lifelines.readthedocs.io/en/latest/)

Runs survival analysis, including Kaplan-Meier, Nelson-Aalen, and regression models.

- Downloads / mo: 2.2M
- Stars: 2.6K
- Last release: 0.30.3
- License: MIT
- Capabilities: [From the lifelines docs](https://lifelines.readthedocs.io/en/latest/)

```sh
pip install lifelines
```

**autonlab/auton-survival** (372 stars)

[autonlab/auton-survival](https://github.com/autonlab/auton-survival) 

```python
def _fit_cph(features, outcomes, val_data, random_seed, **hyperparams):
  """Fit a linear Cox Proportional Hazards model to a given dataset.

  Parameters
  -----------
  features : pd.DataFrame
      A pandas dataframe with rows corresponding to individual samples and
      columns as covariates.
  outcomes : pd.DataFrame
      A pandas dataframe with columns 'time' and 'event'.
  val_data : tuple
      A tuple of the validation dataset features and outcomes of
      'time' and 'event'.
  random_seed : int
      Controls the reproducibility of called functions.
  hyperparams : Optional arguments
      Options include:
      - 'l2' : float, default=1e-3
          Penalizer

  Returns
  -----------
  Trained instance of the Cox Proportional Hazards model.

  """

  from lifelines import CoxPHFitter

  data = outcomes.join(features)
  penalizer = hyperparams.get('l2', 1e-3)

  return CoxPHFitter(penalizer=penalizer).fit(data,
                                              duration_col='time',
                                              event_col='event')

```

[auton_survival/estimators.py](https://github.com/autonlab/auton-survival/blob/5dde465f7223601717abddc1d075e837707c403b/auton_survival/estimators.py#L236-L269) · [More projects using lifelines →](https://dashboard.exa.ai/playground/search?q=lifelines%20GitHub%20projects)

**Quickstart**

```python
from lifelines.datasets import load_waltons
df = load_waltons() # returns a Pandas DataFrame

T = df['T']
E = df['E']

from lifelines import KaplanMeierFitter
kmf = KaplanMeierFitter()
kmf.fit(T, event_observed=E)  # or, more succinctly, kmf.fit(T, E)

```

From [Quickstart.html](https://lifelines.readthedocs.io/en/latest/Quickstart.html)

### StatsForecast

[GitHub](https://github.com/Nixtla/statsforecast) · [PyPI](https://pypi.org/project/statsforecast) · [Docs](https://nixtlaverse.nixtla.io/statsforecast/)

Forecasts time series with statistical models.

- Downloads / mo: 1.8M
- Stars: 5.0K
- Last release: 2.1.1
- License: Apache-2.0
- Capabilities: [From the StatsForecast docs](https://nixtlaverse.nixtla.io/statsforecast/)

```sh
pip install statsforecast
```

**unit8co/darts** (9.6K stars)

[unit8co/darts](https://github.com/unit8co/darts) 

```python
def _fit(
    self,
    series: TimeSeries,
    future_covariates: TimeSeries | None = None,
    verbose: bool | None = None,
):
    super()._fit(series, future_covariates, verbose=verbose)
    self._assert_univariate(series)
    series = self.training_series

    if self._supports_native_future_covariates or future_covariates is None:
        target = series.values(copy=False).flatten()
    else:
        # perform OLS and get in-sample residuals
        self._linreg = LinearRegressionModel(
            lags_future_covariates=[0],
            use_static_covariates=False,
        )
        self._linreg.fit(
            series, future_covariates=future_covariates, verbose=verbose
        )
        target = self._get_target_residuals(series, future_covariates)

    self.model.fit(
        target,
        X=(
            future_covariates.values(copy=False)
            if future_covariates is not None
            and self._supports_native_future_covariates
            else None
        ),
    )
    return self

```

[darts/models/forecasting/sf_model.py](https://github.com/unit8co/darts/blob/1a040e78687468d926bbbae12f5befcd72d294e8/darts/models/forecasting/sf_model.py#L187-L219) · [More projects using StatsForecast →](https://dashboard.exa.ai/playground/search?q=statsforecast%20GitHub%20projects)

**Quickstart**

```python
from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA
from statsforecast.utils import AirPassengersDF

df = AirPassengersDF
sf = StatsForecast(
    models=[AutoARIMA(season_length=12)],
    freq='ME',
)
sf.fit(df)
sf.predict(h=12, level=[95])

```

From [README.md](https://github.com/Nixtla/statsforecast/blob/main/README.md)

### pmdarima

[GitHub](https://github.com/alkaline-ml/pmdarima) · [PyPI](https://pypi.org/project/pmdarima) · [Docs](https://alkaline-ml.com/pmdarima/)

Selects ARIMA models automatically, like the forecast package's auto.arima.

- Downloads / mo: 1.7M
- Stars: 1.7K
- Last release: 2.1.1
- License: MIT
- Capabilities: [From the pmdarima docs](https://alkaline-ml.com/pmdarima/)

```sh
pip install pmdarima
```

**sktime/sktime** (10.1K stars)

[sktime/sktime](https://github.com/sktime/sktime) 

```python
def _fit(self, y, X, fh):
    """Fit to training data.

    Parameters
    ----------
    y : pd.Series
        Target time series to which to fit the forecaster.
    fh : int, list, np.array or ForecastingHorizon, optional (default=None)
        The forecasters horizon with the steps ahead to predict.
    X : pd.DataFrame, optional (default=None)
        Exogenous variables are ignored

    Returns
    -------
    self : returns an instance of self.
    """
    self._cur_y = y
    self._cur_X = X
    if X is not None:
        X = X.loc[y.index]
    # statsmodels >= 0.15 raises on out-of-sample prediction if the index
    # is not supported, e.g., an integer index not starting at 0,
    # so we pass a RangeIndex in this case. Predictions are re-indexed in _predict.
    y_fit = y
    if pd.api.types.is_integer_dtype(y.index) and not isinstance(
        y.index, pd.RangeIndex
    ):
        y_fit = y.reset_index(drop=True)
        if X is not None:
            X = X.reset_index(drop=True)
    self._forecaster = self._instantiate_model()
    self._forecaster.fit(y_fit, X=X)
    self._y_name = y.name
    return self

```

[sktime/forecasting/base/adapters/_pmdarima.py](https://github.com/sktime/sktime/blob/7304dab8a5c5c071c990687a5e5993033e8adbc2/sktime/forecasting/base/adapters/_pmdarima.py#L48-L81) · [More projects using pmdarima →](https://dashboard.exa.ai/playground/search?q=pmdarima%20GitHub%20projects)

**Quickstart**

```python
import pmdarima as pm
from pmdarima.model_selection import train_test_split

# Load/split your data
y = pm.datasets.load_wineind()
train, test = train_test_split(y, train_size=150)

# Fit your model
model = pm.auto_arima(train, seasonal=True, m=12)

```

From [README.md](https://github.com/alkaline-ml/pmdarima/blob/master/README.md)

## FAQ

### Which Python statistics library should I use?

[SciPy](#scipy) suits probability distributions, correlations, and statistical tests. [statsmodels](#statsmodels) suits regression, time series, and survival models with inference. [lifelines](#lifelines) suits survival analysis. [Prophet](#prophet) suits forecasts with trend and seasonality.

### What is statsmodels?

[statsmodels](#statsmodels) estimates statistical models and runs hypothesis tests, with formula-based regression workflows. Its array-based OLS interface leaves the intercept out by default.

### What is StatsForecast?

[StatsForecast](#statsforecast) is a time series forecasting suite of statistical models, with automatic ARIMA and ETS model selection.

### SciPy vs statsmodels: which should I use?

[SciPy](#scipy) covers probability distributions, correlations, and statistical tests. [statsmodels](#statsmodels) adds model estimation and formula-based regression.

### What is Prophet?

[Prophet](#prophet) forecasts time series with trend and seasonality components. Its default fit is a point estimate, with optional full Bayesian sampling through Stan.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python statistics libraries SciPy statsmodels Pingouin PyMC statistical tests regression Bayesian code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
