Repository navigation
BUG: Accept missing observations in string categorical inputs - #877
jackiectl2 wants to merge 2 commits into
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
bashtage
left a comment
There was a problem hiding this comment.
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.
-
PanelDatahas the same check inconvert_columns, soPanelOLSwith the same column still raisesTypeError: exog: Exog must contain numbers, strings or categories .... #858 fixed missing categoricals in bothIVDataandPanelData; 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):
-
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)
-
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.
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):
The full estimator suite, documentation build and other pandas/Python versions were not run. No GPU is required.