Skip to content

BUG: mean overflows for integer dtypes (fixes #10155) #10172

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 1 commit into from
May 30, 2015
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.17.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ Bug Fixes
- Bug in ``Categorical`` repr with ``display.width`` of ``None`` in Python 3 (:issue:`10087`)


- Bug in ``mean()`` where integer dtypes can overflow (:issue:`10172`)
- Bug where Panel.from_dict does not set dtype when specified (:issue:`10058`)
- Bug in ``Timestamp``'s' ``microsecond``, ``quarter``, ``dayofyear``, ``week`` and ``daysinmonth`` properties return ``np.int`` type, not built-in ``int``. (:issue:`10050`)
- Bug in ``NaT`` raises ``AttributeError`` when accessing to ``daysinmonth``, ``dayofweek`` properties. (:issue:`10096`)
Expand Down
23 changes: 16 additions & 7 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
is_complex_dtype, is_integer_dtype,
is_bool_dtype, is_object_dtype,
is_datetime64_dtype, is_timedelta64_dtype,
is_datetime_or_timedelta_dtype,
is_datetime_or_timedelta_dtype, _get_dtype,
is_int_or_datetime_dtype, is_any_int_dtype)


Expand Down Expand Up @@ -254,8 +254,16 @@ def nansum(values, axis=None, skipna=True):
@bottleneck_switch()
def nanmean(values, axis=None, skipna=True):
values, mask, dtype, dtype_max = _get_values(values, skipna, 0)
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_max))
count = _get_counts(mask, axis)

dtype_sum = dtype_max
dtype_count = np.float64
if is_integer_dtype(dtype):
dtype_sum = np.float64
elif is_float_dtype(dtype):
dtype_sum = dtype
dtype_count = dtype
count = _get_counts(mask, axis, dtype=dtype_count)
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))

if axis is not None and getattr(the_sum, 'ndim', False):
the_mean = the_sum / count
Expand Down Expand Up @@ -557,15 +565,16 @@ def _maybe_arg_null_out(result, axis, mask, skipna):
return result


def _get_counts(mask, axis):
def _get_counts(mask, axis, dtype=float):
dtype = _get_dtype(dtype)
if axis is None:
return float(mask.size - mask.sum())
return dtype.type(mask.size - mask.sum())

count = mask.shape[axis] - mask.sum(axis)
try:
return count.astype(float)
return count.astype(dtype)
except AttributeError:
return np.array(count, dtype=float)
return np.array(count, dtype=dtype)


def _maybe_null_out(result, axis, mask):
Expand Down
28 changes: 27 additions & 1 deletion pandas/tests/test_nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import numpy as np

from pandas.core.common import isnull
from pandas.core.common import isnull, is_integer_dtype
import pandas.core.nanops as nanops
import pandas.util.testing as tm

Expand Down Expand Up @@ -323,6 +323,32 @@ def test_nanmean(self):
allow_complex=False, allow_obj=False,
allow_str=False, allow_date=False, allow_tdelta=True)

def test_nanmean_overflow(self):
# GH 10155
# In the previous implementation mean can overflow for int dtypes, it
# is now consistent with numpy
from pandas import Series

# numpy < 1.9.0 is not computing this correctly
Copy link
Contributor

Choose a reason for hiding this comment

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

what does numpy do in < 1.9.0?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

for numpy < 1.9.0: (wrong result)

In [1]: import numpy as np

In [2]: np.__version__
Out[2]: '1.8.2'

In [3]: a = 20150515061816532

In [4]: arr = np.array(np.ones(500) * a, dtype=np.int64)

In [5]: arr.mean()
Out[5]: 20150515061816464.0

numpy >= 1.9.0: (correct result)

In [1]: import numpy as np

In [2]: np.__version__
Out[2]: '1.9.0'

In [3]: a = 20150515061816532

In [4]: arr = np.array(np.ones(500) * a, dtype=np.int64)

In [5]: arr.mean()
Out[5]: 20150515061816532.0

Copy link
Contributor

Choose a reason for hiding this comment

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

oh, ok

from distutils.version import LooseVersion
if LooseVersion(np.__version__) >= '1.9.0':
for a in [2 ** 55, -2 ** 55, 20150515061816532]:
s = Series(a, index=range(500), dtype=np.int64)
result = s.mean()
np_result = s.values.mean()
self.assertEqual(result, a)
self.assertEqual(result, np_result)
self.assertTrue(result.dtype == np.float64)

# check returned dtype
for dtype in [np.int16, np.int32, np.int64, np.float16, np.float32, np.float64]:
s = Series(range(10), dtype=dtype)
result = s.mean()
if is_integer_dtype(dtype):
self.assertTrue(result.dtype == np.float64)
else:
self.assertTrue(result.dtype == dtype)

def test_nanmedian(self):
self.check_funs(nanops.nanmedian, np.median,
allow_complex=False, allow_str=False, allow_date=False,
Expand Down