Skip to content

add test for "Allow definition of pd.CategoricalDtype with a specific categories.dtype" #32115

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

Merged
merged 4 commits into from
Mar 2, 2020
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
8 changes: 8 additions & 0 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
----------
categories : sequence, optional
Must be unique, and must not contain any nulls.
The categories are stored in an Index,
and if an index is provided the dtype of that index will be used.
ordered : bool or None, default False
Whether or not this categorical is treated as a ordered categorical.
None can be used to maintain the ordered value of existing categoricals when
Expand Down Expand Up @@ -210,6 +212,12 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
3 NaN
dtype: category
Categories (2, object): [b < a]

An empty CategoricalDtype with a specific dtype can be created
by providing an empty index. As follows,

>>> pd.CategoricalDtype(pd.DatetimeIndex([])).categories.dtype
dtype('<M8[ns]')
"""

# TODO: Document public vs. private API
Expand Down
14 changes: 13 additions & 1 deletion pandas/tests/dtypes/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,14 @@
)

import pandas as pd
from pandas import Categorical, CategoricalIndex, IntervalIndex, Series, date_range
from pandas import (
Categorical,
CategoricalIndex,
DatetimeIndex,
IntervalIndex,
Series,
date_range,
)
import pandas._testing as tm
from pandas.core.arrays.sparse import SparseArray, SparseDtype

Expand Down Expand Up @@ -172,6 +179,11 @@ def test_is_boolean(self, categories, expected):
assert is_bool_dtype(cat) is expected
assert is_bool_dtype(cat.dtype) is expected

def test_dtype_specific_categorical_dtype(self):
expected = "datetime64[ns]"
result = str(Categorical(DatetimeIndex([])).categories.dtype)
assert result == expected


class TestDatetimeTZDtype(Base):
@pytest.fixture
Expand Down