std() groupby Pandas 问题

std() groupby Pandas issue

这会是一个错误吗?当我对 groupby 对象使用 describe() 或 std() 时,我得到不同的答案

import pandas as pd
import numpy as np
import random as rnd

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
     ...:                           'foo', 'bar', 'foo', 'foo'],
     ...:                    'B' : ['one', 'one', 'two', 'three',
     ...:                           'two', 'two', 'one', 'three'],
     ...:                    'C' : 1*(np.random.randn(8)>0.5),
     ...:                    'D' : np.random.randn(8)})
df.head()

df[['C','D']].groupby(['C'],as_index=False).describe()
# this line gives me the standard deviation of 'C' to be 0,0. Within each    group value of C is constant, so that makes sense. 

df[['C','D']].groupby(['C'],as_index=False).std()
# This line gives me the standard deviation of 'C' to be 0,1. I think this is wrong

有道理。在第二种情况下,您 仅计算列 D.

std

怎么样?这就是 groupby 的工作原理。你

  1. 切片 CD
  2. groupbyC
  3. 致电GroupBy.std

在第 3 步,您没有指定任何列,因此假定 std 是在 不是 石斑鱼的列上计算的...又名,列 D.

至于为什么你看到C0, 1...那是因为你指定了as_index=False,所以C 列插入了来自原始数据帧的值...在本例中为 0, 1.

运行这样就清楚了

df[['C','D']].groupby(['C']).std()

          D
C          
0  0.998201
1       NaN

当您指定 as_index=False 时,您在上面看到的索引将作为 插入。对比一下,

df[['C','D']].groupby(['C'])[['C', 'D']].std()

     C         D
C               
0  0.0  0.998201
1  NaN       NaN

这正是 describe 所提供的,也是您正在寻找的。

即使使用 std(),您也会得到每个组中 C 的零标准差。我刚刚在您的代码中添加了一个种子以使其可复制。我不确定是什么问题 -

import pandas as pd
import numpy as np
import random as rnd

np.random.seed=1987
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
     'foo', 'bar', 'foo', 'foo'],
     'B' : ['one', 'one', 'two', 'three',
     'two', 'two', 'one', 'three'],
     'C' : 1*(np.random.randn(8)>0.5),
     'D' : np.random.randn(8)})
df

df[['C','D']].groupby(['C'],as_index=False).describe()

df[['C','D']].groupby(['C'],as_index=False).std()

再深入一点,如果你看一下继承自DataFrame.describe的groupby的describe源码,

def describe_numeric_1d(series):
            stat_index = (['count', 'mean', 'std', 'min'] +
                          formatted_percentiles + ['max'])
            d = ([series.count(), series.mean(), series.std(), series.min()] +
                 [series.quantile(x) for x in percentiles] + [series.max()])
            return pd.Series(d, index=stat_index, name=series.name)

以上代码显示 describe 仅显示 std() 的结果

我和我的朋友 mukherjees 对这个进行了更多的试验,并确定 std() 确实存在问题。您可以在下面link中看到我们如何显示"std() is not the same as .apply(np.std, ddof=1). " 注意到之后,我们还发现了以下相关错误报告:

https://github.com/pandas-dev/pandas/issues/10355