2017-04-07 62 views
1
>>> df=pd.DataFrame({'c1':[1,1,1,1,2,2,2,2],'c2':['a','b','a','b','a','a','b','b'],'c3':['w','w','x','x','w','x','w','x'],'c4':[90,28,31,10,21,55,49,23]}) 

>>> groups = df.groupby(['c1','c3']) 

>>> groups.apply(lambda x: x[x['c2']=='b'].c4.values/x[x['c2']=='a'].c4.values) 

c1 c2 
1 w [0.31111] 
    x [0.32258] 
2 w [2.33333] 
    x [0.41818] 

有沒有辦法讓上面的操作返回浮動值而不是ndarray?返回花車而不是ndarray在熊貓 - python

c1 c2 
1 w 0.31111 
    x 0.32258 
2 w 2.33333 
    x 0.41818 

回答

2

我認爲你可以輸出轉換爲Series

df = groups.apply(lambda x: pd.Series(x[x['c2']=='b'].c4/x[x['c2']=='a'].c4.values)) 
      .reset_index(level=2, drop=True) 
print (df) 
c1 c3 
1 w  0.311111 
    x  0.322581 
2 w  2.333333 
    x  0.418182 
Name: c4, dtype: float64 
+0

它的偉大工程!再次感謝你的幫助! – HappyPy

+0

很高興能幫到你! – jezrael