2016-08-19 27 views
3

考慮以下df如何將GROUPBY在內部總結與數字和非數字數據類型

df = pd.DataFrame([ 
     ['X', 'a', 0, 1], 
     ['X', 'b', 2, 3], 
     ['X', 'c', 4, 5], 
     ['Y', 'a', 6, 7], 
     ['Y', 'b', 8, 9], 
     ['Y', 'c', 10, 11], 
    ], columns=['One', 'Two', 'Three', 'Four']) 
df 

enter image description here

df.dtypes 

One  object 
Two  object 
Three  int64 
Four  int64 
dtype: object 

當我df.sum()我得到了sum會做在各的列。

df.sum() 

One  XXXYYY 
Two  abcabc 
Three  30 
Four   36 
dtype: object 

但是,我想在groupby內執行此操作。我期望這個工作

df.groupby('One').sum() 

enter image description here

但它似乎只對數字列求和。什麼是執行與df.sum()相同的總和的便捷方式?

我期望這個結果

pd.concat([df.set_index('One').loc[i].sum() for i in ['X', 'Y']], 
      axis=1, keys=['X', 'Y']).T.rename_axis('One') 

enter image description here

+0

好吧,我給予好評的。 ';) – jezrael

+0

和問題太;) – jezrael

回答

4

有可能通過使用agglambda來實現你想要的結果:

In [6]: 
df.groupby('One').agg(lambda x: x.sum()) 

Out[6]: 
    Two Three Four 
One     
X abc  6  9 
Y abc  24 27