Skip to content

Series.value_counts: Preserve original ordering #24302

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 7 commits into from
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ Backwards incompatible API changes
- :func:`read_csv` will now raise a ``ValueError`` if a column with missing values is declared as having dtype ``bool`` (:issue:`20591`)
- The column order of the resultant :class:`DataFrame` from :meth:`MultiIndex.to_frame` is now guaranteed to match the :attr:`MultiIndex.names` order. (:issue:`22420`)
- :func:`pd.offsets.generate_range` argument ``time_rule`` has been removed; use ``offset`` instead (:issue:`24157`)
- :meth:`Series.value_counts` returns the counts in the same ordering as the original series when using ``sort=False`` (:issue:`12679`)
Copy link
Member

Choose a reason for hiding this comment

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

Move to 0.25


Percentage change on groupby
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Expand Down
9 changes: 8 additions & 1 deletion pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,7 @@ def value_counts(values, sort=True, ascending=False, normalize=False,

"""
from pandas.core.series import Series, Index
from pandas.core.dtypes.generic import ABCCategoricalIndex
name = getattr(values, 'name', None)

if bins is not None:
Expand Down Expand Up @@ -695,19 +696,25 @@ def value_counts(values, sort=True, ascending=False, normalize=False,
if is_extension_array_dtype(values) or is_sparse(values):

# handle Categorical and sparse,
result = Series(values)._values.value_counts(dropna=dropna)
vals = Series(values)
uniq = vals._values.unique()
result = vals._values.value_counts(dropna=dropna)
result.name = name
counts = result.values

else:
keys, counts = _value_counts_arraylike(values, dropna)
uniq = unique(values)

if not isinstance(keys, Index):
keys = Index(keys)
result = Series(counts, index=keys, name=name)

if sort:
result = result.sort_values(ascending=ascending)
elif bins is None:
if not isinstance(result.index, ABCCategoricalIndex):
Copy link
Contributor

Choose a reason for hiding this comment

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

this should not be necessary

Copy link
Author

Choose a reason for hiding this comment

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

It unfortunately is for cases, where the categories contain more elements than the values: #24302 (comment)

Copy link
Contributor

Choose a reason for hiding this comment

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

it is not necessary otherwise the impl is incorrect

categoricals uniq already handles this

Copy link
Author

Choose a reason for hiding this comment

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

It doesn't seem so as unique does not contain d in this example:


In [31]: s = pd.Series(pd.Categorical(list('baabc'), categories=list('abcd')))                                                                                                                                                                

In [32]: s.value_counts()                                                                                                                                                                                                                     
Out[32]: 
b    2
a    2
c    1
d    0
dtype: int64

In [33]: pd.unique(s)                                                                                                                                                                                                                         
Out[33]: 
[b, a, c]
Categories (3, object): [b, a, c]

Copy link
Author

Choose a reason for hiding this comment

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

https://github.com/pandas-dev/pandas/blob/master/pandas/core/arrays/categorical.py#L2267 also mentions that unused categories are not returned.

It would be consistent to not return it in the value_counts in the above example as well, but would change the current behaviour... What do you think?

result = result.reindex(uniq)

if normalize:
result = result / float(counts.sum())
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/test_algos.py
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,42 @@ def test_value_counts_uint64(self):
if not compat.is_platform_32bit():
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("sort",
[pytest.param(True, marks=pytest.mark.xfail), False])
@pytest.mark.parametrize("ascending", [True, False])
def test_value_counts_single_occurance(self, sort, ascending):
# GH 12679
# All items occour exactly once.
# No matter if sorted or not, the resulting values should be in
# the same order.
expected = Series(list('bacdef'))

# Guarantee the same index if value_counts(sort=False) is used
vc = expected.value_counts(sort=sort, ascending=ascending)
result = Series(vc.index)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("ascending", [True, False])
def test_value_counts_nonsorted_double_occurance(self, ascending):
# GH 12679
# 'a' is there twice. Sorted, it should be there at the top.
s = Series(list('bacaef'))
expected = Series(list('bacef'))

vc = s.value_counts(sort=False, ascending=ascending)
result = Series(vc.index)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("ascending, expected",
[(True, Series(list('abcef'))),
(False, Series(list('bcefa')))])
@pytest.mark.xfail(reason="sort=True does not guarantee the same order")
def test_value_counts_sorted_double_occurance(self, ascending, expected):
# GH 12679
s = Series(list('bacaef'))
vc = s.value_counts(sort=True, ascending=ascending)
tm.assert_series_equal(Series(vc.index), expected)


class TestDuplicated(object):

Expand Down