Skip to content

Commit 3d92ac3

Browse files
lukemanleycodamuse
authored andcommitted
BUG/PERF: MultiIndex.value_counts returning flat index (pandas-dev#49558)
1 parent 8e0aa38 commit 3d92ac3

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

doc/source/whatsnew/v2.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,7 @@ MultiIndex
617617
- Bug in :meth:`MultiIndex.union` not sorting when sort=None and index contains missing values (:issue:`49010`)
618618
- Bug in :meth:`MultiIndex.append` not checking names for equality (:issue:`48288`)
619619
- Bug in :meth:`MultiIndex.symmetric_difference` losing extension array (:issue:`48607`)
620+
- Bug in :meth:`MultiIndex.value_counts` returning a :class:`Series` indexed by flat index of tuples instead of a :class:`MultiIndex` (:issue:`49558`)
620621
-
621622

622623
I/O

pandas/core/algorithms.py

+8
Original file line numberDiff line numberDiff line change
@@ -871,6 +871,14 @@ def value_counts(
871871
result.name = name
872872
counts = result._values
873873

874+
elif isinstance(values, ABCMultiIndex):
875+
# GH49558
876+
levels = list(range(values.nlevels))
877+
result = Series(index=values).groupby(level=levels, dropna=dropna).size()
878+
# TODO: allow index names to remain (see discussion in GH49497)
879+
result.index.names = [None] * values.nlevels
880+
counts = result._values
881+
874882
else:
875883
values = _ensure_arraylike(values)
876884
keys, counts = value_counts_arraylike(values, dropna)

pandas/tests/base/test_value_counts.py

-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,6 @@ def test_value_counts(index_or_series_obj):
2929
counter = collections.Counter(obj)
3030
expected = Series(dict(counter.most_common()), dtype=np.int64, name=obj.name)
3131
expected.index = expected.index.astype(obj.dtype)
32-
if isinstance(obj, pd.MultiIndex):
33-
expected.index = Index(expected.index)
3432

3533
if not isinstance(result.dtype, np.dtype):
3634
# i.e IntegerDtype

0 commit comments

Comments
 (0)