From 2be0f6b9121e2b3993ce95145016cdc3f499920e Mon Sep 17 00:00:00 2001 From: Raphael Fakhri <153192858+RaphaelFakhri@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:56:17 +0000 Subject: [PATCH] Support pandas nullable dtypes in safe_issubdtype --- patsy/test_highlevel.py | 17 +++++++++++++++++ patsy/util.py | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/patsy/test_highlevel.py b/patsy/test_highlevel.py index 2fad925c..fb618a57 100644 --- a/patsy/test_highlevel.py +++ b/patsy/test_highlevel.py @@ -997,3 +997,20 @@ def test_NAActioon_pandas_string_index(): dm2 = dmatrix(di, data2, 0, return_type="dataframe") assert np.allclose(dm2, [[1.0, 6.0, 4.0], [1.0, 7.0, 5.0]]) assert list(dm2.columns) == ["Intercept", "x", "z"] + + +def test_pandas_nullable_dtypes(): + if not have_pandas or not hasattr(pandas, "BooleanDtype"): + return + data = pandas.DataFrame( + { + "b": pandas.array([True, False, True], dtype="boolean"), + "i": pandas.array([1, 2, 1], dtype="Int64"), + } + ) + dm = dmatrix("b", data) + assert dm.design_info.column_names == ["Intercept", "b[T.True]"] + assert np.allclose(dm, [[1, 1], [1, 0], [1, 1]]) + dm = dmatrix("C(i)", data) + assert len(dm.design_info.column_names) == 2 + assert np.allclose(dm, [[1, 0], [1, 1], [1, 0]]) diff --git a/patsy/util.py b/patsy/util.py index d666d38f..2c21a62f 100644 --- a/patsy/util.py +++ b/patsy/util.py @@ -818,6 +818,9 @@ def safe_issubdtype(dt1, dt2): # The second condition is needed to support pandas >= 3 (!) if safe_is_pandas_categorical_dtype(dt1) or safe_is_pandas_string_dtype(dt1): return False + # pandas nullable dtypes (e.g. "boolean", "Int64") are not numpy dtypes, + # but they record the numpy dtype they correspond to. + dt1 = getattr(dt1, "numpy_dtype", dt1) return np.issubdtype(dt1, dt2) @@ -831,6 +834,11 @@ def test_safe_issubdtype(): bad_dtype = pandas.Series(["a", "b"], dtype="category") assert not safe_issubdtype(bad_dtype, np.integer) + if have_pandas and hasattr(pandas, "BooleanDtype"): + assert safe_issubdtype(pandas.BooleanDtype(), np.bool_) + assert safe_issubdtype(pandas.Int64Dtype(), np.integer) + assert not safe_issubdtype(pandas.Int64Dtype(), np.bool_) + def no_pickling(*args, **kwargs): raise NotImplementedError(