Skip to content

Support for use of Enums in MultiIndex #21348

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
wants to merge 25 commits into from
Closed
Show file tree
Hide file tree
Changes from 15 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 ci/appveyor-27.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ dependencies:
- pytest
- pytest-xdist
- moto
- enum34
1 change: 1 addition & 0 deletions ci/circle-27-compat.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
- enum34
Copy link
Contributor

Choose a reason for hiding this comment

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

can you remove from all but 1 of the 27 compat tests (the travis-27) one

Copy link
Author

Choose a reason for hiding this comment

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

done

- pip:
- html5lib==1.0b2
- beautifulsoup4==4.2.1
Expand Down
1 change: 1 addition & 0 deletions ci/travis-27-locale.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
- enum34
- pip:
- html5lib==1.0b2
- beautifulsoup4==4.2.1
1 change: 1 addition & 0 deletions ci/travis-27.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ dependencies:
- pytest
- pytest-xdist
- moto
- enum34
- pip:
- backports.lzma
- cpplint
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.23.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Indexing
- Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`)
- Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`)
- Bug in :meth:`MultiIndex.sort_index` which was not guaranteed to sort correctly with ``level=1``; this was also causing data misalignment in particular :meth:`DataFrame.stack` operations (:issue:`20994`, :issue:`20945`, :issue:`21052`)
- Bug in :func:`pandas.core.arrays.categorical._factorize_from_iterable` inappropriately caused ``TypeError`` to be raised when an ``Enum`` was used as a factor in a ``MultiIndex`` (:issue:`21298`)
Copy link
Member

Choose a reason for hiding this comment

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

@gfyoung I'm stumped by this whatsnew conflict, any thoughts?

@benediamond : I would actually move your whatsnew addition to 0.24.0. That will suffice. 😄

Copy link
Author

@benediamond benediamond Jun 8, 2018

Choose a reason for hiding this comment

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

I've gone ahead and just removed it---I'm not sure where it belongs, as it appeared that this PR (when it was passing) was slated for the next milestone.

Copy link
Member

Choose a reason for hiding this comment

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

@benediamond : I would put it in 0.24.0, as I suggested above. We will need a whatsnew for this for sure, and that would be the best place to put it.

Copy link
Author

Choose a reason for hiding this comment

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

@gfyoung Done. this one didn't create merge conflicts, thankfully

-

I/O
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -2523,7 +2523,7 @@ def _factorize_from_iterable(values):
ordered=values.ordered)
codes = values.codes
else:
cat = Categorical(values, ordered=True)
cat = Categorical(values, ordered=False)
Copy link
Member

Choose a reason for hiding this comment

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

Interesting that this didn't cause any testing issues...

Copy link
Author

@benediamond benediamond Jun 9, 2018

Choose a reason for hiding this comment

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

Yes, it's striking. It's possible that thatindexes.multi is essentially the only caller of categorical._factorize_from_iterable, and that the calls that multi makes happen to be such that within Categorical's constructor, control is always routed so that the only time that ordered is used is to incorrectly raise the TypeError on lines 352-354. That's my best-guess explanation, at least.

categories = cat.categories
codes = cat.codes
return codes, categories
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/indexes/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3307,3 +3307,39 @@ def test_duplicate_multiindex_labels(self):
with pytest.raises(ValueError):
ind.set_levels([['A', 'B', 'A', 'A', 'B'], [2, 1, 3, -2, 5]],
inplace=True)

def test_use_enum_in_multiindex(self):
Copy link
Contributor

Choose a reason for hiding this comment

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

can you use @td.skip_if_no('enum') here (then do the actual import inside), we have to guard against the tests being run on 2.7 w/o the compat library (by a user).

Copy link
Author

Choose a reason for hiding this comment

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

# GH 21298
# Allow use of Enums as one of the factors in a MultiIndex.
from enum import Enum
from pandas.core.algorithms import take_1d
Copy link
Member

@gfyoung gfyoung Jun 8, 2018

Choose a reason for hiding this comment

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

By "top", @jreback meant move the imports to "top of the file" 😄

Copy link
Author

Choose a reason for hiding this comment

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

Hah whoops. done


# See https://github.com/pandas-dev/pandas/blob/
# 0c65c57a279e755ab7093db925d1e580f9878dae/pandas/util/testing.py#L793-L799.
# We cannot simply use tm.assert_index_equal, as the "expected" index
# cannot actually be built yet.
def _get_ilevel_values(index, level):
Copy link
Contributor

Choose a reason for hiding this comment

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

what is all this for?

simply construct the expected index directly

Copy link
Author

Choose a reason for hiding this comment

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

The thought here is that the expected index cannot be constructed directly, due to the exact bug I'm trying to fix. Thus instead I create an expected "level", and verify that it matches the relevant level of df's index. This is done by replicating a sub-step of tm.assert_index_equal.

# accept level number only
unique = index.levels[level]
labels = index.labels[level]
filled = take_1d(
unique.values,
labels, fill_value=unique._na_value
)
values = unique._shallow_copy(filled, name=index.names[level])
return values
Copy link
Member

@gfyoung gfyoung Jun 8, 2018

Choose a reason for hiding this comment

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

Given that you use this function only once, I think this abstraction is unnecessary as @jreback alluded to in an earlier comment.

Copy link
Author

Choose a reason for hiding this comment

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

Ok, amended. Thanks for your guidance.


MyEnum = Enum("MyEnum", "A B")
Copy link
Contributor

Choose a reason for hiding this comment

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

you would have to add enum34 (the 2.7 backport) in our 2.7 builds

(pandas) bash-3.2$ grep python=2.7 ci/*.yaml
appveyor-27.yaml:  - python=2.7.*
circle-27-compat.yaml:  - python=2.7*
travis-27-locale.yaml:  - python=2.7
travis-27.yaml:  - python=2.7*

Copy link
Author

Choose a reason for hiding this comment

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

ok, I've hopefully done this correctly.

df = pd.DataFrame(columns=pd.MultiIndex.from_product(iterables=[
MyEnum,
[1, 2]
]))
exp_index_0 = pd.Index([MyEnum.A, MyEnum.A, MyEnum.B, MyEnum.B],
dtype='object')
Copy link
Contributor

Choose a reason for hiding this comment

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

this is pretty complicated, why cannot you just directly construct the Index here?

Copy link
Author

Choose a reason for hiding this comment

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

tm.assert_index_equal(_get_ilevel_values(df.columns, 0), exp_index_0)

expected = df.copy()
df = df.append({(MyEnum.A, 1): "abc", (MyEnum.B, 2): "xyz"},
ignore_index=True)
expected.loc[0, [(MyEnum.A, 1), (MyEnum.B, 2)]] = 'abc', 'xyz'
tm.assert_frame_equal(df, expected)