Skip to content

BUG/PERF: MultiIndex.value_counts returning flat index #49558

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 5 commits into from
Nov 9, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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 doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ MultiIndex
- Bug in :meth:`MultiIndex.union` not sorting when sort=None and index contains missing values (:issue:`49010`)
- Bug in :meth:`MultiIndex.append` not checking names for equality (:issue:`48288`)
- Bug in :meth:`MultiIndex.symmetric_difference` losing extension array (:issue:`48607`)
- Bug in :meth:`MultiIndex.value_counts` returning a :class:`Series` indexed by flat index of tuples (:issue:`49558`)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
- Bug in :meth:`MultiIndex.value_counts` returning a :class:`Series` indexed by flat index of tuples (:issue:`49558`)
- Bug in :meth:`MultiIndex.value_counts` returning a :class:`Series` indexed by flat index of tuples instead of a :class:`MultiIndex` (:issue:`49558`)

Nit

Copy link
Member Author

Choose a reason for hiding this comment

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

updated, thanks

-

I/O
Expand Down
6 changes: 6 additions & 0 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,12 @@ def value_counts(
result.name = name
counts = result._values

elif isinstance(values, ABCMultiIndex):
# GH49558
levels = list(range(values.nlevels))
result = Series(index=values).groupby(level=levels, dropna=dropna).size()
counts = result._values

else:
values = _ensure_arraylike(values)
keys, counts = value_counts_arraylike(values, dropna)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/test_algos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1350,6 +1350,16 @@ def test_value_counts_uint64(self):

tm.assert_series_equal(result, expected)

def test_value_counts_multiindex(self):
# GH49558
mi = MultiIndex.from_tuples(
tuples=[(1, "a"), (2, "b"), (3, "c"), (2, "b")],
names=["foo", "bar"],
)
result = algos.value_counts(mi)
expected = Series(data=[2, 1, 1], index=mi.take([1, 0, 2]))
tm.assert_series_equal(result, expected)


class TestDuplicated:
def test_duplicated_with_nas(self):
Expand Down