首页 > 解决方案 > Pandas GroupBy 每个月然后根据列中的字符串进行小计计数

问题描述

我希望获得每月已完成交易占总交易的百分比。以前我的数据只有一个月,通过以下方式解决:

total_trades = df['state'].count()
RFQ_Hit_Rate = done_trades / total_trades
RFQ_Hit_Rate = round(RFQ_Hit_Rate, 6)

现在有 12 个月的数据,所以我需要更新代码。新数据

dfHit_Rate_All = df[['Year_Month','state']].copy()
dfHit_Rate_All = dfHit_Rate_All.groupby(['Year_Month','state']).size().reset_index(name='count')

  Year_Month    state           Counts  
     2017-11    Customer Reject  1  
     2017-11    Customer Timeout 2  
     2017-11    Dealer Reject    3  
     2017-12    Dealer Timeout   4  
     2017-12    Done             5  
     2017-12    Done             6  
     2018-01    Tied Covered     7  
     2018-01    Tied Done        8  
     2018-01    Tied Traded Away 9  
     2018-02    Traded Away      10 
     2018-02    Done             11 
     2018-02    Customer Reject  12 

对于每个月,找到总交易、完成交易的总数并计算比率。请注意,任何带有“完成”的字符串都是完成的交易,即 [df['state'].str.contains('Done'):

Year_Month  Total_state_count   Total_state_count_Done  Done_To_Total_Ratio
2017-11               6                        0                0%
2017-12               15                       11               73%
2018-01               24                       8                33%
2018-02               33                       11               33%

标签: pythonpandasgroup-by

解决方案


我认为需要agg用元组聚合 - 带有聚合函数的新列名:

agg = [('Total_state_count_Done',lambda x: x.str.contains('Done').sum()), 
       ('Total_state_count', 'size')]
df = df.groupby('Year_Month')['state'].agg(agg)

对于新列除法和倍数100

df['Done_To_Total_Ratio'] = df['Total_state_count_Done'].div(df['Total_state_count']).mul(100)

print (df)
            Total_state_count_Done  Total_state_count  Done_To_Total_Ratio
Year_Month                                                                
2017-11                          0                  3             0.000000
2017-12                          2                  3            66.666667
2018-01                          1                  3            33.333333
2018-02                          1                  3            33.333333

如果需要将最后一列转换为整数并添加百分比:

df['Done_To_Total_Ratio'] = (df['Total_state_count_Done']
                                  .div(df['Total_state_count'])
                                  .mul(100)
                                  .astype(int)
                                  .astype(str)
                                  .add('%'))

print (df)
            Total_state_count_Done  Total_state_count Done_To_Total_Ratio
Year_Month                                                               
2017-11                          0                  3                  0%
2017-12                          2                  3                 66%
2018-01                          1                  3                 33%
2018-02                          1                  3                 33%

推荐阅读