为什么 np.std() 和 pivot_table(aggfunc=np.std) return 不同的结果
why np.std() and pivot_table(aggfunc=np.std) return the different result
我有一些代码,不明白为什么会出现差异:
np.std() 单独使用时默认ddof=0.
但是为什么在pivot_table(aggfunc=np.std)中作为参数时,它会自动变为ddof=1。
import numpys as np
import pandas as pd
dft = pd.DataFrame({'A': ['one', 'one'],
'B': ['A', 'A'],
'C': ['bar', 'bar'],
'D': [-0.866740402,1.490732028]})
np.std(dft['D'])
#equivalent:np.std([-0.866740402,1.490732028]) (which:defaualt ddof=0)
#the result: 1.178736215
dft.pivot_table(index=['A', 'B'],columns='C',aggfunc=np.std)
#equivalent:np.std([-0.866740402,1.490732028],ddof=1)
#the result:1.666985
pivot 使用 DataFrame.groupby.agg 并且当您提供聚合函数时,它将尝试弄清楚如何 _aggregate
.
arg=np.std
will get handled here,相关代码为
f = self._get_cython_func(arg)
if f and not args and not kwargs:
return getattr(self, f)(), None
隐藏在 DataFrame class 中的是 table:
pd.DataFrame()._cython_table
#OrderedDict([(<function sum>, 'sum'),
# (<function max>, 'max'),
# ...
# (<function numpy.std>, 'std'),
# (<function numpy.nancumsum>, 'cumsum')])
pd.DataFrame()._cython_table.get(np.std)
#'std'
所以np.std
只用于select调用的属性,默认的ddof
完全忽略,取而代之的是pandas
默认的[=18] =]被使用。
getattr(dft['D'], 'std')()
#1.6669847417133286
我有一些代码,不明白为什么会出现差异:
np.std() 单独使用时默认ddof=0.
但是为什么在pivot_table(aggfunc=np.std)中作为参数时,它会自动变为ddof=1。
import numpys as np
import pandas as pd
dft = pd.DataFrame({'A': ['one', 'one'],
'B': ['A', 'A'],
'C': ['bar', 'bar'],
'D': [-0.866740402,1.490732028]})
np.std(dft['D'])
#equivalent:np.std([-0.866740402,1.490732028]) (which:defaualt ddof=0)
#the result: 1.178736215
dft.pivot_table(index=['A', 'B'],columns='C',aggfunc=np.std)
#equivalent:np.std([-0.866740402,1.490732028],ddof=1)
#the result:1.666985
pivot 使用 DataFrame.groupby.agg 并且当您提供聚合函数时,它将尝试弄清楚如何 _aggregate
.
arg=np.std
will get handled here,相关代码为
f = self._get_cython_func(arg)
if f and not args and not kwargs:
return getattr(self, f)(), None
隐藏在 DataFrame class 中的是 table:
pd.DataFrame()._cython_table
#OrderedDict([(<function sum>, 'sum'),
# (<function max>, 'max'),
# ...
# (<function numpy.std>, 'std'),
# (<function numpy.nancumsum>, 'cumsum')])
pd.DataFrame()._cython_table.get(np.std)
#'std'
所以np.std
只用于select调用的属性,默认的ddof
完全忽略,取而代之的是pandas
默认的[=18] =]被使用。
getattr(dft['D'], 'std')()
#1.6669847417133286