[英]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.