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 3 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 @@ -1634,6 +1634,7 @@ Other

- Bug where C variables were declared with external linkage causing import errors if certain other C libraries were imported before Pandas. (:issue:`24113`)
- Require at least 0.28.2 version of ``cython`` to support read-only memoryviews (:issue:`21688`)
- :meth:`Series.value_counts` returns the counts in the same ordering as the original series when using ``sort=False`` (:issue:`12679`)
Copy link
Contributor

Choose a reason for hiding this comment

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

move to api breaking changes

Copy link
Author

Choose a reason for hiding this comment

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

Done and pushed


.. _whatsnew_0.24.0.contributors:

Expand Down
6 changes: 5 additions & 1 deletion pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ def value_counts(values, sort=True, ascending=False, normalize=False,
value_counts : Series

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

if bins is not None:
Expand Down Expand Up @@ -708,6 +708,10 @@ def value_counts(values, sort=True, ascending=False, normalize=False,

if sort:
result = result.sort_values(ascending=ascending)
elif bins is None:
uniq = unique(values)
Copy link
Contributor

Choose a reason for hiding this comment

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

so do
uniq = uniques(values) for the non-EA case (above)
and do uniq = Series(values)._values.unique() for the EA case. though this means computing it twice. maybe have to work on that.

Copy link
Author

Choose a reason for hiding this comment

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

I added it above, although it is not computed twice now. Did you mean it like this?

if not isinstance(result.index, CategoricalIndex):
Copy link
Contributor

Choose a reason for hiding this comment

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

why is this check needed? (or maybe it just needs to be for an ordered categorical)

Copy link
Author

Choose a reason for hiding this comment

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

The issue was the test TestCategoricalSeriesAnalytics.test_value_counts:

cats = Categorical(list('abcccb'), categories=list('cabd'))
s = Series(cats, name='xxx')
res = s.value_counts(sort=False)

which returns 0 for the dcategory as well, which is not in the unique(values). Is there another possibility to get access to that initial categorical from the index?

result = result.reindex(uniq)

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

def test_value_counts_nonsorted_single_occurance(self):
Copy link
Contributor

Choose a reason for hiding this comment

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

paramterize on sort

Copy link
Author

Choose a reason for hiding this comment

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

Done and pushed

# GH 12679
# All items occour exactly once.
# No matter if sorted or not, the resulting values should be in
# the same order.
s = Series(list('bacdef'))

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

@pytest.mark.xfail(reason="sort=True does not guarantee the same order")
Copy link
Contributor

Choose a reason for hiding this comment

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

why is this xfail?

Copy link
Author

Choose a reason for hiding this comment

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

I could not get it working for the sort=True case and left the tests only for possible future fixing... Would you prefer deleting them and adding them when sort=True works as well?

def test_value_counts_sorted_single_occurance(self):
# GH 12679
s = Series(list('bacdef'))
# Guarantee does not hold yet for the sort=True case
vc = s.value_counts(sort=True, ascending=False)
tm.assert_series_equal(Series(vc.index), s)
vc = s.value_counts(sort=True, ascending=True)
tm.assert_series_equal(Series(vc.index), s)

def test_value_counts_nonsorted_double_occurance(self):
Copy link
Contributor

Choose a reason for hiding this comment

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

parametrize these.

Copy link
Author

Choose a reason for hiding this comment

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

The double_occurance tests have different expected results and I wouldn't parametrize it due to that. Or would you do this as well in that case?

Copy link
Contributor

Choose a reason for hiding this comment

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

I c, ok then, parameterize over ascending though

# GH 12679
# 'a' is there twice. Sorted, it should be there at the top.
s = Series(list('bacaef'))
ref_nonsorted = Series(list('bacef'))

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

@pytest.mark.xfail(reason="sort=True does not guarantee the same order")
def test_value_counts_sorted_double_occurance(self):
# GH 12679
s = Series(list('bacaef'))
ref_sorted = Series(list('abcef'))
# Guarantee does not hold yet for the sort=True case
vc = s.value_counts(sort=True, ascending=False)
tm.assert_series_equal(Series(vc.index), ref_sorted)
vc = s.value_counts(sort=True, ascending=True)
tm.assert_series_equal(Series(vc.index), ref_sorted)


class TestDuplicated(object):

Expand Down