Pandas Group每个月然后根据列中的字符串计算小计

时间:2018-06-06 06:38:21

标签: python pandas group-by

我希望将完成交易的百分比换算为每月的总交易量。以前我的数据仅用了一个月,并通过以下方式解决:

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 

每个月查找总交易数,总完成交易数并计算比率。注意任何带有'Done'的字符串都是完成交易,即[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%

1 个答案:

答案 0 :(得分:1)

我认为需要通过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%