【问题标题】:Groupby Pandas DataFrame and calculate mean and stdev of one column and add the std as a new column with reset_indexGroupby Pandas DataFrame 并计算一列的平均值和标准偏差,并将标准添加为带有 reset_index 的新列
【发布时间】:2014-10-28 01:08:29
【问题描述】:

我有一个如下所示的 Pandas DataFrame:

   a      b      c      d
0  Apple  3      5      7
1  Banana 4      4      8
2  Cherry 7      1      3
3  Apple  3      4      7

我想按“a”列对行进行分组,同时将“c”列中的值替换为分组行中值的平均值,并添加另一列,其平均值为“c”列中值的标准偏差计算出来的。 'b' 或 'd' 列中的值对于被分组的所有行都是恒定的。因此,所需的输出将是:

   a      b      c      d      e
0  Apple  3      4.5    7      0.707107
1  Banana 4      4      8      0
2  Cherry 7      1      3      0

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以使用groupby-agg operation:

    In [38]: result = df.groupby(['a'], as_index=False).agg(
                          {'c':['mean','std'],'b':'first', 'd':'first'})
    

    然后重命名列并重新排序:

    In [39]: result.columns = ['a','c','e','b','d']
    
    In [40]: result.reindex(columns=sorted(result.columns))
    Out[40]: 
            a  b    c  d         e
    0   Apple  3  4.5  7  0.707107
    1  Banana  4  4.0  8       NaN
    2  Cherry  7  1.0  3       NaN
    

    Pandas 默认计算样本标准。计算总体标准:

    def pop_std(x):
        return x.std(ddof=0)
    
    result = df.groupby(['a'], as_index=False).agg({'c':['mean',pop_std],'b':'first', 'd':'first'})
    
    result.columns = ['a','c','e','b','d']
    result.reindex(columns=sorted(result.columns))
    

    产量

            a  b    c  d    e
    0   Apple  3  4.5  7  0.5
    1  Banana  4  4.0  8  0.0
    2  Cherry  7  1.0  3  0.0
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2021-09-06
    • 1970-01-01
    • 2014-03-21
    相关资源
    最近更新 更多