简洁版本:
之所以不同是因为pandas
uses bottleneck
(如果已安装)调用时mean
操作,而不是仅仅依靠numpy
. bottleneck
大概被使用,因为它看起来比numpy
(至少在我的机器上),但以精度为代价。它们恰好与 64 位版本匹配,但在 32 位版本中有所不同(这是有趣的部分)。
长版:
仅通过检查这些模块的源代码很难判断发生了什么(它们非常复杂,即使对于像这样的简单计算也是如此)mean
,事实证明数值计算很困难)。最好使用调试器来避免大脑编译和此类错误。调试器不会犯逻辑错误,它会告诉你exactly这是怎么回事。
这是我的一些堆栈跟踪(由于没有 RNG 种子,值略有不同):
可以重现(Windows):
>>> import numpy as np; import pandas as pd
>>> x=np.random.normal(-9.,.005,size=900000)
>>> df=pd.DataFrame(x,dtype='float32',columns=['x'])
>>> df['x'].mean()
-9.0
>>> x.mean()
-9.0000037501099754
>>> x.astype(np.float32).mean()
-9.0000029
没有什么特别的事情发生numpy
的版本。这是pandas
版本有点古怪。
让我们看看里面df['x'].mean()
:
>>> def test_it_2():
... import pdb; pdb.set_trace()
... df['x'].mean()
>>> test_it_2()
... # Some stepping/poking around that isn't important
(Pdb) l
2307
2308 if we have an ndarray as a value, then simply perform the operation,
2309 otherwise delegate to the object
2310
2311 """
2312 -> delegate = self._values
2313 if isinstance(delegate, np.ndarray):
2314 # Validate that 'axis' is consistent with Series's single axis.
2315 self._get_axis_number(axis)
2316 if numeric_only:
2317 raise NotImplementedError('Series.{0} does not implement '
(Pdb) delegate.dtype
dtype('float32')
(Pdb) l
2315 self._get_axis_number(axis)
2316 if numeric_only:
2317 raise NotImplementedError('Series.{0} does not implement '
2318 'numeric_only.'.format(name))
2319 with np.errstate(all='ignore'):
2320 -> return op(delegate, skipna=skipna, **kwds)
2321
2322 return delegate._reduce(op=op, name=name, axis=axis, skipna=skipna,
2323 numeric_only=numeric_only,
2324 filter_type=filter_type, **kwds)
所以我们找到了问题所在,但现在事情变得有点奇怪:
(Pdb) op
<function nanmean at 0x000002CD8ACD4488>
(Pdb) op(delegate)
-9.0
(Pdb) delegate_64 = delegate.astype(np.float64)
(Pdb) op(delegate_64)
-9.000003749978807
(Pdb) delegate.mean()
-9.0000029
(Pdb) delegate_64.mean()
-9.0000037499788075
(Pdb) np.nanmean(delegate, dtype=np.float64)
-9.0000037499788075
(Pdb) np.nanmean(delegate, dtype=np.float32)
-9.0000029
注意delegate.mean()
and np.nanmean
output -9.0000029
与类型float32
, not -9.0
as pandas
nanmean
做。经过一番探索,您可以找到源代码pandas
nanmean
in pandas.core.nanops
。有趣的是,它实际上看起来像这样should匹配numpy
首先。我们来看看pandas
nanmean
:
(Pdb) import inspect
(Pdb) src = inspect.getsource(op).split("\n")
(Pdb) for line in src: print(line)
@disallow('M8')
@bottleneck_switch()
def nanmean(values, axis=None, skipna=True):
values, mask, dtype, dtype_max = _get_values(values, skipna, 0)
dtype_sum = dtype_max
dtype_count = np.float64
if is_integer_dtype(dtype) or is_timedelta64_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
ct_mask = count == 0
if ct_mask.any():
the_mean[ct_mask] = np.nan
else:
the_mean = the_sum / count if count > 0 else np.nan
return _wrap_results(the_mean, dtype)
这是一个(简短的)版本bottleneck_switch
装饰器:
import bottleneck as bn
...
class bottleneck_switch(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, alt):
bn_name = alt.__name__
try:
bn_func = getattr(bn, bn_name)
except (AttributeError, NameError): # pragma: no cover
bn_func = None
...
if (_USE_BOTTLENECK and skipna and
_bn_ok_dtype(values.dtype, bn_name)):
result = bn_func(values, axis=axis, **kwds)
这被称为alt
as the pandas
nanmean
函数,所以bn_name
is 'nanmean'
,这是从中获取的 attrbottleneck
module:
(Pdb) l
93 result = np.empty(result_shape)
94 result.fill(0)
95 return result
96
97 if (_USE_BOTTLENECK and skipna and
98 -> _bn_ok_dtype(values.dtype, bn_name)):
99 result = bn_func(values, axis=axis, **kwds)
100
101 # prefer to treat inf/-inf as NA, but must compute the fun
102 # twice :(
103 if _has_infs(result):
(Pdb) n
> d:\anaconda3\lib\site-packages\pandas\core\nanops.py(99)f()
-> result = bn_func(values, axis=axis, **kwds)
(Pdb) alt
<function nanmean at 0x000001D2C8C04378>
(Pdb) alt.__name__
'nanmean'
(Pdb) bn_func
<built-in function nanmean>
(Pdb) bn_name
'nanmean'
(Pdb) bn_func(values, axis=axis, **kwds)
-9.0
假装那样bottleneck_switch()
装饰器一秒钟都不存在。我们实际上可以看到手动调用该函数(无需bottleneck
)会给你相同的结果numpy
:
(Pdb) from pandas.core.nanops import _get_counts
(Pdb) from pandas.core.nanops import _get_values
(Pdb) from pandas.core.nanops import _ensure_numeric
(Pdb) values, mask, dtype, dtype_max = _get_values(delegate, skipna=skipna)
(Pdb) count = _get_counts(mask, axis=None, dtype=dtype)
(Pdb) count
900000.0
(Pdb) values.sum(axis=None, dtype=dtype) / count
-9.0000029
不过,如果你有的话,那永远不会被调用bottleneck
安装。相反,bottleneck_switch()
装饰器反而会爆炸nanmean
功能与bottleneck
的版本。这就是差异所在(有趣的是,它与float64
不过,情况):
(Pdb) import bottleneck as bn
(Pdb) bn.nanmean(delegate)
-9.0
(Pdb) bn.nanmean(delegate.astype(np.float64))
-9.000003749978807
bottleneck
据我所知,仅用于速度。我假设他们正在采取某种捷径nanmean
函数,但我没有深入研究它(有关此主题的详细信息,请参阅@ead 的答案)。您可以看到它通常比numpy
根据他们的基准:https://github.com/kwgoodman/bottleneck https://github.com/kwgoodman/bottleneck。显然,为这种速度付出的代价是精度。
瓶颈实际上更快吗?
当然看起来像这样(至少在我的机器上)。
In [1]: import numpy as np; import pandas as pd
In [2]: x=np.random.normal(-9.8,.05,size=900000)
In [3]: y_32 = x.astype(np.float32)
In [13]: %timeit np.nanmean(y_32)
100 loops, best of 3: 5.72 ms per loop
In [14]: %timeit bn.nanmean(y_32)
1000 loops, best of 3: 854 µs per loop
这可能对pandas
在这里引入一个标志(一个用于速度,另一个用于更好的精度,默认值是速度,因为这是当前的实现)。一些用户更关心计算的准确性而不是计算发生的速度。
HTH.