Skip to content

BUG: Accept missing observations in string categorical inputs - #877

Open
jackiectl2 wants to merge 2 commits into
bashtage:mainfrom
jackiectl2:fix-string-categorical-missing
Open

jackiectl2 wants to merge 2 commits into
bashtage:mainfrom
jackiectl2:fix-string-categorical-missing

Conversation

@jackiectl2

Copy link
Copy Markdown
Contributor

IVData accepts string columns and converts them to categoricals, but its all-strings check also tests missing entries. A country/industry column containing None therefore raises a type error, while explicitly casting the same column to category correctly marks the observation as missing.

Check the observed entries when recognizing a string column. Keep the existing rejection of an entirely untyped missing column, and leave conversion/missing-row handling to the categorical path.

Validation (CPU, Python 3.12):

  • Six string/dtype regressions and a real IV2SLS fit fail before the fix.
  • Entire IV data test file: 31 passed.
  • Ruff lint/format and git diff --check pass.
  • Informational mypy reports 61 diagnostics in four files; normalized diagnostics match the unchanged base. This is not a clean type-check result.

The full estimator suite, documentation build and other pandas/Python versions were not run. No GPU is required.

Signed-off-by: Tianlang (Jackie) Chen <305351710+jackiectl2@users.noreply.github.com>
Signed-off-by: Tianlang (Jackie) Chen <305351710+jackiectl2@users.noreply.github.com>
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (d7980a7) to head (387189e).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #877   +/-   ##
=======================================
  Coverage   99.69%   99.69%           
=======================================
  Files         202      202           
  Lines       38871    38890   +19     
  Branches     2501     2501           
=======================================
+ Hits        38752    38771   +19     
  Misses         51       51           
  Partials       68       68           
Flag Coverage Δ
adder 99.68% <100.00%> (+<0.01%) ⬆️
subtractor 99.68% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. The IV part is right: a string column with a missing value now takes the categorical path, the rows are dropped with a MissingValueWarning, and the IV2SLS estimates equal OLS with explicit dummies on the observed rows.

  1. PanelData has the same check in convert_columns, so PanelOLS with the same column still raises TypeError: exog: Exog must contain numbers, strings or categories .... #858 fixed missing categoricals in both IVData and PanelData; please do the same here:

    --- a/linearmodels/panel/data.py
    +++ b/linearmodels/panel/data.py
    @@ -157,7 +157,11 @@ def convert_columns(s: Series, drop_first: bool) -> linearmodels.typing.AnyPanda
             A DataFrame of dummy variables, named ``name.category``, if s contains
             strings or is categorical. Otherwise, s.
         """
    -    if is_string_dtype(s.dtype) and s.map(lambda v: isinstance(v, str)).all():
    +    if (
    +        is_string_dtype(s.dtype)
    +        and s.notna().any()
    +        and s.map(lambda v: isinstance(v, str), na_action="ignore").all()
    +    ):
             s = s.astype("category")
    
         if isinstance(s.dtype, pd.CategoricalDtype):
  2. The notna().any() guard isn't tested: without it the tests still pass, and an all-missing string column becomes a frame with no columns. These tests pass with the change above, and each all-missing test fails if its guard is removed:

    # linearmodels/tests/iv/test_data.py
    @pytest.mark.parametrize("dtype", ["object", "str", "string"])
    def test_strings_all_missing_values_raise(dtype: str) -> None:
        values = pd.Series([None, None, None], dtype=dtype, name="country")
        with pytest.raises(ValueError, match="categorical data permitted"):
            IVData(values)
    # linearmodels/tests/panel/test_data.py, next to test_categorical_missing_values_in_a_model
    @pytest.mark.parametrize("dtype", ["object", "str", "string"])
    @pytest.mark.parametrize("drop_first", [True, False])
    def test_strings_with_missing_values_match_categoricals(dtype, drop_first):
        index = MultiIndex.from_product([["a", "b"], [0, 1]])
        group = Series(["first", None, "second", "first"], dtype=dtype, index=index)
        values = DataFrame({"group": group})
        data = PanelData(values, drop_first=drop_first)
        expected = PanelData(values.astype("category"), drop_first=drop_first)
        assert_frame_equal(data.dataframe, expected.dataframe)
        assert_equal(data.isnull.to_numpy(), [False, True, False, False])
    
    
    @pytest.mark.parametrize("dtype", ["object", "str", "string"])
    def test_strings_all_missing_values(dtype):
        # Without an observed string there are no categories, so the column is kept as
        # a column of missing values
        index = MultiIndex.from_product([["a", "b"], [0, 1]])
        values = DataFrame({"group": Series([None] * 4, dtype=dtype, index=index)})
        data = PanelData(values)
        assert list(data.dataframe.columns) == ["group"]
        assert data.isnull.all()
    
    
    def test_string_missing_values_in_a_model():
        rng = np.random.default_rng(877)
        index = MultiIndex.from_product([range(20), range(10)])
        nobs = len(index)
        labels = rng.choice(["a", "b", "c"], nobs).astype(object)
        labels[rng.choice(nobs, 20, replace=False)] = None
        x = rng.standard_normal(nobs)
        y = 1 + x + 0.5 * (labels == "b") + rng.standard_normal(nobs)
        frame = DataFrame({"y": y, "const": 1.0, "x": x, "g": labels}, index=index)
        with pytest.warns(MissingValueWarning, match="missing values"):
            res = PooledOLS(frame.y, frame[["const", "x", "g"]]).fit()
        as_categorical = frame.assign(g=Categorical(labels))
        with pytest.warns(MissingValueWarning, match="missing values"):
            expected = PooledOLS(
                as_categorical.y, as_categorical[["const", "x", "g"]]
            ).fit()
        assert res.nobs == 180
        assert_allclose(res.params, expected.params, rtol=1e-12)
  3. Release note, under "Bug fixes":

    - A string column with missing values (``None`` or ``NaN``) is treated as a categorical
      column in ``IVData`` and ``PanelData``, so that the observations with a missing value
      are dropped with a ``MissingValueWarning``. 7.1 raised a ``ValueError`` in the IV models
      and a ``TypeError`` in the panel models (:issue:`877`).

Minor: assert_series_equal(result.params, expected.params) uses pandas' default tolerance (rtol 1e-5); assert_allclose with an explicit rtol would match the other tests.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants