Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/tabmat/categorical_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,8 @@ def _extract_codes_and_categories(cat_vec):
elif _is_polars(cat_vec):
if not _is_polars(cat_vec.dtype):
cat_vec = cat_vec.cast(pl.Categorical)
categories = cat_vec.cat.get_categories().to_numpy()
indices = cat_vec.to_physical().fill_null(-1).to_numpy()
categories = cat_vec.cat.to_local().cat.get_categories().to_numpy()
indices = cat_vec.cat.to_local().to_physical().fill_null(-1).to_numpy()
else:
indices, categories = pd.factorize(cat_vec, sort=True)
return indices, categories
Expand Down
13 changes: 12 additions & 1 deletion tests/test_categorical_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

import numpy as np
import pandas as pd
import polars as pl
import pytest

from tabmat.categorical_matrix import CategoricalMatrix
from tabmat.categorical_matrix import CategoricalMatrix, _extract_codes_and_categories


@pytest.fixture
Expand Down Expand Up @@ -202,3 +203,13 @@ def test_categorical_indexing(drop_first, missing, cat_missing_method):
dummy_na=cat_missing_method == "convert" and missing,
).to_numpy()[:, [0, 1]]
np.testing.assert_allclose(mat[:, [0, 1]].toarray(), expected)


def test_polars_non_contiguous_codes():
str_series = ["labrador", "boxer", "beagle"]
with pl.StringCache():
_ = pl.Series(["beagle", "poodle", "labrador"], dtype=pl.Categorical)
cat_series = pl.Series(str_series, dtype=pl.Categorical)

indices, categories = _extract_codes_and_categories(cat_series)
np.testing.assert_array_equal(str_series, categories[indices].tolist())