Skip to content

BUG: Categorical(Index) passed as categories #17888

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 8 commits into from
Oct 18, 2017
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,7 @@ Categorical
- Bug in the categorical constructor with empty values and categories causing the ``.categories`` to be an empty ``Float64Index`` rather than an empty ``Index`` with object dtype (:issue:`17248`)
- Bug in categorical operations with :ref:`Series.cat <categorical.cat>` not preserving the original Series' name (:issue:`17509`)
- Bug in :func:`DataFrame.merge` failing for categorical columns with boolean/int data types (:issue:`17187`)
- Bug in constructing a ``Categorical``/``CategoricalDtype`` when the specified ``categories`` where of categorical type (:issue:`17884`).
Copy link
Contributor

@jreback jreback Oct 16, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move this to the CDT issue, IOW the sub-section (as its actually not an independent bug) and better there.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bug also exists for Categorical and CateforicalIndex and was already present in current released 0.20.3. So not directly related to the CDT rework (although the bug is present in CDT as well). But not that important, can also move if you want.


.. _whatsnew_0210.pypy:

Expand Down
17 changes: 10 additions & 7 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re
import numpy as np
from pandas import compat
from pandas.core.dtypes.generic import ABCIndexClass
from pandas.core.dtypes.generic import ABCIndexClass, ABCCategoricalIndex


class ExtensionDtype(object):
Expand Down Expand Up @@ -170,16 +170,16 @@ def _from_categorical_dtype(cls, dtype, categories=None, ordered=None):
return cls(categories, ordered)

def _finalize(self, categories, ordered, fastpath=False):
from pandas.core.indexes.base import Index

if ordered is None:
ordered = False
else:
self._validate_ordered(ordered)

if categories is not None:
categories = Index(categories, tupleize_cols=False)
# validation
self._validate_categories(categories, fastpath=fastpath)
self._validate_ordered(ordered)
categories = self._validate_categories(categories,
fastpath=fastpath)

self._categories = categories
self._ordered = ordered

Expand Down Expand Up @@ -316,7 +316,10 @@ def _validate_categories(categories, fastpath=False):
from pandas import Index

if not isinstance(categories, ABCIndexClass):
categories = Index(categories)
categories = Index(categories, tupleize_cols=False)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be an elif and instead should use is_categorical

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't the point of the ABC ones to avoid imports from itself ? (as is_categorical uses CategoricalDtype)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback Can you answer this one? No problem to change it if you think it is better, but it seems to me using isinstance(categories, ABCCategoricalIndex) is consistent with the use of isinstance(categories, ABCIndexClass) just above (also in readability of the code)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, yeah I guess you have to do this. but you can also check isinstance(categories, (ABCCateoricalIndex, ABCCategorical)) is more generic.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated to use isinstance(categories, (ABCCateoricalIndex, ABCCategorical)) first and then only to check for Index

if isinstance(categories, ABCCategoricalIndex):
categories = categories.categories

if not fastpath:

Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/dtypes/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,10 @@ def test_str_vs_repr(self):
# Py2 will have unicode prefixes
pat = r"CategoricalDtype\(categories=\[.*\], ordered=False\)"
assert re.match(pat, repr(c1))

def test_categorical_categories(self):
# GH17884
c1 = CategoricalDtype(pd.Categorical(['a', 'b']))
tm.assert_index_equal(c1.categories, pd.Index(['a', 'b']))
c1 = CategoricalDtype(pd.CategoricalIndex(['a', 'b']))
tm.assert_index_equal(c1.categories, pd.Index(['a', 'b']))
24 changes: 24 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,18 @@ def test_contructor_from_categorical_string(self):
result = Categorical(values, categories=['a', 'b', 'c'], ordered=True)
tm.assert_categorical_equal(result, expected)

def test_constructor_with_categorical_categories(self):
# GH17884
expected = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])

result = pd.Categorical(
['a', 'b'], categories=pd.Categorical(['a', 'b', 'c']))
tm.assert_categorical_equal(result, expected)

result = pd.Categorical(
['a', 'b'], categories=pd.CategoricalIndex(['a', 'b', 'c']))
tm.assert_categorical_equal(result, expected)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Categorical and CategoricalIndex have been imported, so you can remove the pd. here, if you feel that's cleaner.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, thanks! (updated)


def test_from_codes(self):

# too few categories
Expand Down Expand Up @@ -560,6 +572,18 @@ def f():
codes = np.random.choice([0, 1], 5, p=[0.9, 0.1])
pd.Categorical.from_codes(codes, categories=["train", "test"])

def test_from_codes_with_categorical_categories(self):
# GH17884
expected = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])

result = pd.Categorical.from_codes(
[0, 1], categories=pd.Categorical(['a', 'b', 'c']))
tm.assert_categorical_equal(result, expected)

result = pd.Categorical.from_codes(
[0, 1], categories=pd.CategoricalIndex(['a', 'b', 'c']))
tm.assert_categorical_equal(result, expected)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same regarding pd.


@pytest.mark.parametrize('dtype', [None, 'category'])
def test_from_inferred_categories(self, dtype):
cats = ['a', 'b']
Expand Down