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

Categorical: don't sort the categoricals if Categorical(..., ordered=False) #9347

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 1 addition & 1 deletion pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa

if categories is None:
try:
codes, categories = factorize(values, sort=True)
codes, categories = factorize(values, sort=ordered if not ordered is None else True)
Copy link
Member

Choose a reason for hiding this comment

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

More succinctly, this could be ordered is None or ordered

# If the underlying data structure was sortable, and the user doesn't want to
# "forget" this order, the categorical also is sorted/ordered
if ordered is None:
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,20 @@ def f():
c_old2 = Categorical([0, 1, 2, 0, 1, 2], [1, 2, 3])
cat = Categorical([1,2], categories=[1,2,3])

# if the categorical is constructed without ordering, use the "order of appearance" in
# the categories instead of sorting the lexiographicaly.
# see https://github.com/mwaskom/seaborn/issues/361 for a discussion on this topic
c1 = Categorical(["a", "c", "b", "a"], ordered=False)
self.assert_numpy_array_equal(c1.categories, np.array(["a","c","b"]))
# mae sure that construction with (implicit) ordered=True sorts the categories
c2 = Categorical(["a", "c", "b", "a"])
self.assert_numpy_array_equal(c2.categories, np.array(["a","b","c"]))
c2 = Categorical(["a", "c", "b", "a"], ordered=True)
self.assert_numpy_array_equal(c2.categories, np.array(["a","b","c"]))
# ensure that the order in the categories is preserved when setting ordered=False
c2.ordered = False
self.assert_numpy_array_equal(c2.categories, np.array(["a","b","c"]))

def test_constructor_with_generator(self):
# This was raising an Error in isnull(single_val).any() because isnull returned a scalar
# for a generator
Expand Down