Skip to content

BUG: value_counts not working correctly on ExtensionArrays #33674

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 14 commits into from
May 1, 2020
2 changes: 2 additions & 0 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,8 @@ def value_counts(
result = result.sort_values(ascending=ascending)

if normalize:
if not isinstance(counts, np.ndarray):
counts = counts.to_numpy()
result = result / float(counts.sum())

return result
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,13 @@ def test_value_counts_na():
result = arr.value_counts(dropna=True)
expected = pd.Series([2, 1], index=["a", "b"], dtype="Int64")
tm.assert_series_equal(result, expected)


def test_normalize_value_counts():
result = (
pd.Series(list("abcd"), dtype="string")
.value_counts(normalize=True)
.sort_index()
)
expected = pd.Series([0.25, 0.25, 0.25, 0.25], index=["a", "b", "c", "d"])
tm.assert_series_equal(expected, result)