2014-10-28 33 views
9

一個新的專欄中,我有一個熊貓數據框如下:GROUPBY熊貓數據幀,並計算平均值和一列的STDEV並添加性病與reset_index

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

我想GROUP BY列的行「一',而'c'列中的值由分組行中的值的平均值替換,並添加另一列,其中已計算平均值的'c'列中的值的標準偏差。列「b」或「d」中的值對於所有被分組的行都是不變的。所以,期望的輸出將是:

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

什麼是實現這一目標的最佳方法?

回答

13

你可以使用一個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 

注意均值和分組c值的標準方差不同。


熊貓在默認情況下計算樣本標準偏差。爲了計算人口標準:

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 
+0

謝謝@unutbu! – kkhatri99 2014-10-28 02:33:23

+0

@unutbu:你會PLZ檢查這個問題http://stackoverflow.com/questions/26601001/calculate-std-manually-using-groupby-pandas-dataframe – user3378649 2014-10-28 04:40:37