Skip to content

REGR: Categorical with np.str_ categories #31528

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 7 commits into from
Feb 4, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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: 1 addition & 1 deletion doc/source/whatsnew/v1.0.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Bug fixes

Categorical
^^^^^^^^^^^

- Fixed regression in :class:`Categorical` construction with ``numpy.str_`` categories (:issue:`31499`)
-
-

Expand Down
8 changes: 6 additions & 2 deletions pandas/_libs/hashtable_class_helper.pxi.in
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,9 @@ cdef class StringHashTable(HashTable):
val = values[i]

if isinstance(val, str):
v = get_c_string(val)
# GH#31499 if we have a np.str_ get_c_string wont recognize
# it as a str, even though isinstance does.
v = get_c_string(<str>val)
else:
v = get_c_string(self.na_string_sentinel)
vecs[i] = v
Expand Down Expand Up @@ -703,7 +705,9 @@ cdef class StringHashTable(HashTable):
val = values[i]

if isinstance(val, str):
v = get_c_string(val)
# GH#31499 if we have a np.str_ get_c_string wont recognize
# it as a str, even though isinstance does.
v = get_c_string(<str>val)
else:
v = get_c_string(self.na_string_sentinel)
vecs[i] = v
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/arrays/categorical/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,11 @@ def test_constructor_str_unknown(self):
with pytest.raises(ValueError, match="Unknown dtype"):
Categorical([1, 2], dtype="foo")

def test_constructor_np_strs(self):
# GH#31499 Hastable.map_locations needs to work on np.str_ objects
cat = pd.Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")])
Copy link
Contributor

Choose a reason for hiding this comment

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

actually, I think we should be santizing these inputs on Index construction; we already do this for Series IIRC (deep in block manager i think). Can you see if that's better (as its a more maintainable long term soln). Not averse to your change, but that's after we already saved the inputs.

assert all(isinstance(x, np.str_) for x in cat.categories)

def test_constructor_from_categorical_with_dtype(self):
dtype = CategoricalDtype(["a", "b", "c"], ordered=True)
values = Categorical(["a", "b", "d"])
Expand Down