Skip to content

Commit 5460b19

Browse files
rushabh-vroberthdevries
authored andcommitted
TST: Allow definition of pd.CategoricalDtype with a specific categories.dtype (pandas-dev#32115)
1 parent d965a6a commit 5460b19

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

pandas/core/dtypes/dtypes.py

+8
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,8 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
175175
----------
176176
categories : sequence, optional
177177
Must be unique, and must not contain any nulls.
178+
The categories are stored in an Index,
179+
and if an index is provided the dtype of that index will be used.
178180
ordered : bool or None, default False
179181
Whether or not this categorical is treated as a ordered categorical.
180182
None can be used to maintain the ordered value of existing categoricals when
@@ -210,6 +212,12 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
210212
3 NaN
211213
dtype: category
212214
Categories (2, object): [b < a]
215+
216+
An empty CategoricalDtype with a specific dtype can be created
217+
by providing an empty index. As follows,
218+
219+
>>> pd.CategoricalDtype(pd.DatetimeIndex([])).categories.dtype
220+
dtype('<M8[ns]')
213221
"""
214222

215223
# TODO: Document public vs. private API

pandas/tests/dtypes/test_dtypes.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,14 @@
2626
)
2727

2828
import pandas as pd
29-
from pandas import Categorical, CategoricalIndex, IntervalIndex, Series, date_range
29+
from pandas import (
30+
Categorical,
31+
CategoricalIndex,
32+
DatetimeIndex,
33+
IntervalIndex,
34+
Series,
35+
date_range,
36+
)
3037
import pandas._testing as tm
3138
from pandas.core.arrays.sparse import SparseArray, SparseDtype
3239

@@ -177,6 +184,11 @@ def test_is_boolean(self, categories, expected):
177184
assert is_bool_dtype(cat) is expected
178185
assert is_bool_dtype(cat.dtype) is expected
179186

187+
def test_dtype_specific_categorical_dtype(self):
188+
expected = "datetime64[ns]"
189+
result = str(Categorical(DatetimeIndex([])).categories.dtype)
190+
assert result == expected
191+
180192

181193
class TestDatetimeTZDtype(Base):
182194
@pytest.fixture

0 commit comments

Comments
 (0)