Skip to content

BUG: fix Series.value_counts with sort=False returns result sorted on values for Series with string dtype #57116

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 3 commits into from
Jan 29, 2024
Merged
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ Conversion

Strings
^^^^^^^
-
- Bug in :meth:`Series.value_counts` would not respect ``sort=False`` for series having ``string`` dtype (:issue:`55224`)
-

Interval
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ def max(self, axis=None, skipna: bool = True, **kwargs) -> Scalar:
def value_counts(self, dropna: bool = True) -> Series:
from pandas.core.algorithms import value_counts_internal as value_counts

result = value_counts(self._ndarray, dropna=dropna).astype("Int64")
result = value_counts(self._ndarray, sort=False, dropna=dropna).astype("Int64")
result.index = result.index.astype(self.dtype)
return result

Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,19 @@ def test_value_counts_with_normalize(dtype):
tm.assert_series_equal(result, expected)


def test_value_counts_sort_false(dtype):
if getattr(dtype, "storage", "") == "pyarrow":
exp_dtype = "int64[pyarrow]"
elif getattr(dtype, "storage", "") == "pyarrow_numpy":
exp_dtype = "int64"
else:
exp_dtype = "Int64"
ser = pd.Series(["a", "b", "c", "b"], dtype=dtype)
result = ser.value_counts(sort=False)
expected = pd.Series([1, 2, 1], index=ser[:3], dtype=exp_dtype, name="count")
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize(
"values, expected",
[
Expand Down