Skip to content
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