【问题标题】:Python Pandas: Groupby and Apply multi-column operationPython Pandas:Groupby 和 Apply 多列操作
【发布时间】:2013-10-23 13:43:07
【问题描述】:

df1 是 4 列的 DataFrame。

我想通过将 df1 与列“A”分组并在列“C”和“D”上进行多列操作来创建一个新的 DataFrame (df2)

“AA”列 = 平均值 (C)+平均值 (D)

列'BB' = std(D)

df1= pd.DataFrame({
    'A' : ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],
    'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
    'C' : np.random.randn(8), 
    'D' : np.random.randn(8)})

   A      B         C         D
0  foo    one  1.652675 -1.983378
1  bar    one  0.926656 -0.598756
2  foo    two  0.131381  0.604803
3  bar  three -0.436376 -1.186363
4  foo    two  0.487161 -0.650876
5  bar    two  0.358007  0.249967
6  foo    one -1.150428  2.275528
7  foo  three  0.202677 -1.408699

def fun1(gg): # this does not work
    return pd.DataFrame({'AA':C.mean()+gg.C.std(), 'BB':gg.C.std()})


dg1 = df1.groupby('A')
df2 = dg1.apply(fun1)

这不起作用。似乎aggregation() 仅适用于Series,并且不可能进行多列操作。 并且 apply() 仅产生具有多列操作的 Series 输出。 有没有其他方法可以产生多列操作的多列输出(DataFrame)?

【问题讨论】:

    标签: python pandas aggregation multiple-columns


    【解决方案1】:

    您的f 函数中有错字吗? AA 应该是 C.mean() + C.std() 还是 C.mean() + D.mean()

    在第一种情况下,AA = C.mean() + C.std(),

    In [91]: df = df1.groupby('A').agg({'C': lambda x: x.mean() + x.std(),
                                        'D': lambda x  x.std()})
    
    In [92]: df
    Out[92]: 
                C         D
    A                      
    bar  1.255506  0.588981
    foo  1.775945  0.442724
    

    对于第二个C.mean() + D.mean(),情况不太好。当你给 groupby 对象上的 .agg 函数一个字典时,我认为没有办法从两列中获取值。

    In [108]: g = df1.groupby('A')
    
    In [109]: df = pd.DataFrame({"AA": g.mean()['C'] + g.mean()['D'], "BB": g.std()['D']})
    
    In [110]: df
    Out[110]: 
               AA        BB
    A                      
    bar  0.532263  0.721351
    foo  0.427608  0.494980
    

    您可能希望将 g.mean() 和 g.std() 分配给临时变量以避免计算两次。

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 1970-01-01
      • 2017-06-01
      • 2017-01-02
      • 2012-12-07
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多