Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bug for categorical pandas index with categories with EA dtype #8481

Merged
merged 3 commits into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ Deprecations
Bug fixes
~~~~~~~~~

- Fix dtype inference for ``pd.CategoricalIndex`` when categories are backed by a ``pd.ExtensionDtype`` (:pull:`8481`)


Documentation
~~~~~~~~~~~~~
Expand Down
2 changes: 2 additions & 0 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ def get_valid_numpy_dtype(array: np.ndarray | pd.Index):
elif hasattr(array, "categories"):
# category isn't a real numpy dtype
dtype = array.categories.dtype
if not is_valid_numpy_dtype(dtype):
dtype = np.dtype("O")
elif not is_valid_numpy_dtype(array.dtype):
dtype = np.dtype("O")
else:
Expand Down
11 changes: 11 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4697,6 +4697,17 @@ def test_from_dataframe_categorical(self) -> None:
assert len(ds["i1"]) == 2
assert len(ds["i2"]) == 2

def test_from_dataframe_categorical_string_categories(self):
phofl marked this conversation as resolved.
Show resolved Hide resolved
cat = pd.CategoricalIndex(
pd.Categorical.from_codes(
np.array([1, 1, 0, 2]),
categories=pd.Index(["foo", "bar", "baz"], dtype="string"),
)
)
ser = pd.Series(1, index=cat)
ds = ser.to_xarray()
assert ds.coords.dtypes["index"] == np.dtype("O")

@requires_sparse
def test_from_dataframe_sparse(self) -> None:
import sparse
Expand Down
Loading