ordinalcorr.hetcor

ordinalcorr.hetcor(data: DataFrame, n_categories: int = 20, n_unique: int | None = None, show_method: bool = False) DataFrame[source]

Estimate the heterogeneous correlation matrix.

The heterogeneous correlation matrix includes:

  • Pearson product-moment correlations between continuous variables

  • Polychoric correlations between ordinal variables

  • Polyserial correlations between continuous and ordinal variables

Parameters:
  • data (pd.DataFrame) –

    A DataFrame containing continuous and/or ordinal variables. Appropriate correlation coefficients are automatically selected based on the types of variables.

    • Columns with dtype int or float and number of unique values less than or equal to n_categories are treated as ordinal variables.

    • Columns with dtype category are treated as ordinal variables if they are ordered.

  • n_categories (int, default=20) – The maximum number of unique values for an integer column to be considered ordinal. If the number of unique values exceeds n_categories, the column is treated as continuous.

  • n_unique (int, optional) – Deprecated alias for n_categories. Will be removed in a future release.

  • show_method (bool, default=False) – If True, the upper triangle of the returned matrix contains the name of the method used to compute each correlation (“polychoric”, “polyserial”, or “pearson”) instead of the numeric value. The diagonal and lower triangle remain numeric. Since the result mixes strings and floats, the returned DataFrame has dtype=object in this case.

Returns:

Estimated heterogeneous correlation matrix. If show_method is True, the upper triangle holds method-name strings and the DataFrame has dtype=object.

Return type:

pd.DataFrame

Examples

>>> from ordinalcorr import hetcor
>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(0)
>>> data = pd.DataFrame({
...     "continuous": np.random.normal(size=90),
...     "ordinal_int": np.repeat([1, 2, 3], 30),
...     "ordinal_float": np.repeat([1.0, 2.0], 45),
...     "ordinal_category": pd.Series(np.repeat([1, 2, 3], 30)).astype("category").cat.as_ordered(),
... })
>>> hetcor(data).round(3)
                  continuous  ordinal_int  ordinal_float  ordinal_category
continuous             1.000       -0.257         -0.254            -0.257
ordinal_int           -0.257        1.000          0.999             1.000
ordinal_float         -0.254        0.999          1.000             0.999
ordinal_category      -0.257        1.000          0.999             1.000
>>> hetcor(data, show_method=True).round(3)
                 continuous ordinal_int ordinal_float ordinal_category
continuous              1.0  polyserial    polyserial       polyserial
ordinal_int       -0.257389         1.0    polychoric       polychoric
ordinal_float     -0.253566    0.998635           1.0       polychoric
ordinal_category  -0.257389    0.999996      0.998647              1.0