簡體   English   中英

將功能應用於熊貓中的分組數據計數

[英]Apply function to grouped data counts in pandas

>>> new_confirmIOC.groupby(['ErrorCode','ResponseType']).OrderID.count()
ErrorCode  ResponseType        
0          CANCEL_ORDER_CONFIRM    80
           TRADE_CONFIRM           31
1          CANCEL_ORDER_CONFIRM    80
           TRADE_CONFIRM           31

如何為錯誤代碼0加上總計的百分比,例如80 / 111、31 / 111,依此類推

我試過了

new_confirmIOC.groupby(['ErrorCode','ResponseType']).OrderID.count().apply(lambda x: x / x.sum())

但這給了我

ErrorCode  ResponseType        
0          CANCEL_ORDER_CONFIRM    1
           TRADE_CONFIRM           1
1          CANCEL_ORDER_CONFIRM    1
           TRADE_CONFIRM           1
Name: OrderID, dtype: int64

我認為您需要按第一層groupby並按sum除法:

df = new_confirmIOC.groupby(['ErrorCode','ResponseType']).OrderID.count()
df = df.groupby(level='ErrorCode').apply(lambda x: x / x.sum())
print (df)
ErrorCode  ResponseType        
0          CANCEL_ORDER_CONFIRM    0.720721
           TRADE_CONFIRM           0.279279
1          CANCEL_ORDER_CONFIRM    0.720721
           TRADE_CONFIRM           0.279279
Name: val, dtype: float64

transform另一種解決方案:

df = df.div(df.groupby(level='ErrorCode').transform('sum'))
print (df)
ErrorCode  ResponseType        
0          CANCEL_ORDER_CONFIRM    0.720721
           TRADE_CONFIRM           0.279279
1          CANCEL_ORDER_CONFIRM    0.720721
           TRADE_CONFIRM           0.279279
Name: val, dtype: float64

謝謝FLab發表評論:

.count的結果是一個Series,因此apply函數將逐個元素地操作。 (不像熊貓DataFrame那樣在整列上)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM