如何使用.agg方法计算pandas中的列平均值

时间:2017-12-28 01:16:53

标签: python pandas dataframe

据我所知,.agg可以很容易地用于计算平均值。例如,如果我有一个数据框df:

df
       one  two  three
   A    1    2      3
   B    4    5      6
   C    7    8      9

我想计算每列的平均值,我可以这样做:

df.agg(np.average)
    one      4.0
    two      5.0
    three    6.0
    dtype: float64

现在,让我们说我只对“一个”的平均值感兴趣。直观地说,我这样写,我期待一个数字4:

df.agg({'one':np.average})   #or df['one'].agg(np.average)

但是,它不是4,而是返回第一列:

       one
    A  1.0
    B  4.0
    C  7.0

为什么?

1 个答案:

答案 0 :(得分:2)

你有很多方法可以做到这一点,你似乎偶然发现了工作的唯一方法。这些都适合我:

df["one"].agg("mean")

df.agg({"one": "mean"})

df["one"].agg(np.mean)

df.agg({"one": np.mean})

查看源代码,看来当您使用average时,它会将DataFrame强制转换为numpy array,然后mean占用该行 - 明智的平均值。因为在基本情况下(没有权重)average实际上会调用mean

def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):

    kwargs = {}
    if keepdims is not np._NoValue:
        kwargs['keepdims'] = keepdims
    if type(a) is not mu.ndarray:
        try:
            mean = a.mean
        except AttributeError:
            pass
        else:
            return mean(axis=axis, dtype=dtype, out=out, **kwargs)

    return _methods._mean(a, axis=axis, dtype=dtype,
                      out=out, **kwargs)

def average(a, axis=None, weights=None, returned=False):

    if (type(a) not in (np.ndarray, np.matrix) and
            issubclass(type(a), np.ndarray)):
        warnings.warn("np.average currently does not preserve subclasses, but "
                      "will do so in the future to match the behavior of most "
                      "other numpy functions such as np.mean. In particular, "
                      "this means calls which returned a scalar may return a "
                      "0-d subclass object instead.",
                      FutureWarning, stacklevel=2)

    if not isinstance(a, np.matrix):
        a = np.asarray(a)

    if weights is None:
        avg = a.mean(axis)
        scl = avg.dtype.type(a.size/avg.size)
    else:
        ...