Skip to content

BUG: value_count(normalize=True, dropna=True) counting missing in denominator, #12558 #12576

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 3 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.18.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ Performance Improvements

Bug Fixes
~~~~~~~~~
- Bug in ``value_counts`` where normalizes over all observations including missing even when ``dropna=True`` (:issue:`12558`)
9 changes: 8 additions & 1 deletion pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,14 @@ def value_counts(values, sort=True, ascending=False, normalize=False,
result = result.sort_values(ascending=ascending)

if normalize:
result = result / float(values.size)
if dropna:
# NaT's dropped above if time, so don't need to do again.
if not com.is_datetime_or_timedelta_dtype(dtype) \
and not is_period and not is_datetimetz:

result = result / float(Series(values).count())
else:
result = result / float(values.size)

return result

Expand Down
27 changes: 27 additions & 0 deletions pandas/tests/test_algos.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,33 @@ def test_dropna(self):
pd.Series([10.3, 5., 5., None]).value_counts(dropna=False),
pd.Series([2, 1, 1], index=[5., 10.3, np.nan]))

def test_normalize(self):
# Issue 12558
tm.assert_series_equal(
pd.Series([5., 10.3, 10.3, 10.3, np.nan]).value_counts(
dropna=True, normalize=True),
pd.Series([0.75, 0.25], index=[10.3, 5.]))

tm.assert_series_equal(
pd.Series([5., 10.3, 10.3, 10.3, np.nan]).value_counts(
dropna=True, normalize=False),
pd.Series([3, 1], index=[10.3, 5.]))

tm.assert_series_equal(
pd.Series([5., 10.3, 10.3, 10.3, np.nan]).value_counts(
dropna=False, normalize=True),
pd.Series([0.6, 0.2, 0.2], index=[10.3, 5., np.nan]))

tm.assert_series_equal(
pd.Series([5., 10.3, 10.3, 10.3, np.nan]).value_counts(
dropna=False, normalize=False),
pd.Series([3, 1, 1], index=[10.3, 5., np.nan]))

s = pd.Series(['2015-01-03T00:00:00.000000000+0000', pd.NaT])
tm.assert_series_equal(
s.value_counts(dropna=True, normalize=True),
pd.Series([1], index=[s.loc[0]]))


class GroupVarTestMixin(object):

Expand Down