Skip to content

BUG: Copy categorical codes if empty (fixes #18051) #18279

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

Closed
Closed
Changes from 1 commit
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
12 changes: 9 additions & 3 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1673,9 +1673,11 @@ def test_unique(self):
exp_cat = Categorical(["b", np.nan, "a"], categories=["b", "a"])
tm.assert_categorical_equal(res, exp_cat)

# GH 18051 unique()._codes should be writeable
cat_nan = Categorical([np.nan])
assert cat_nan.unique()._codes.flags.writeable
# GH 18051
cat = Categorical([np.nan])
res = cat.unique()
exp_cat = Categorical([np.nan], categories=[])
tm.assert_categorical_equal(res, exp_cat)
Copy link
Contributor Author

@ghasemnaddaf ghasemnaddaf Nov 20, 2017

Choose a reason for hiding this comment

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

@jreback , do you mean like this? (This is not failing on 0.21.0 though)

Copy link
Contributor

@topper-123 topper-123 Nov 21, 2017

Choose a reason for hiding this comment

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

There should be a test for

assert pd.Series(pd.Categorical([np.nan])).nunique() == 0

Note that nunique is a method on Series, not Categorical.

Copy link
Contributor Author

@ghasemnaddaf ghasemnaddaf Nov 21, 2017

Choose a reason for hiding this comment

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

Copy link
Contributor

@topper-123 topper-123 Nov 21, 2017

Choose a reason for hiding this comment

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

That looks great IMO.

Also, you mention above that Categorical([np.nan]).unique() doesn't fail in 0.21.0, but pd.Series(pd.Categorical([np.nan])).unique() does fail. So if you could add a test for that as well in the test for series, then IMO the PR is good (but let @jreback make the final call on that).


def test_unique_ordered(self):
# keep categories order when ordered=True
Expand Down Expand Up @@ -2178,6 +2180,10 @@ def test_basic(self):
result = x.person_name.loc[0]
assert result == expected

# GH 18051
s = pd.Series(pd.Categorical([np.nan]))
assert s.nunique() == 0

def test_creation_astype(self):
l = ["a", "b", "c", "a"]
s = pd.Series(l)
Expand Down