python - 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%
解决方案
我认为需要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%
推荐阅读
- swift - 如何在 macOS 中镜像 JPEG 文件
- keras - Keras 中基于输入数据的自定义损失函数
- c - write() 和 read() 如何在 C 中交互(
)? - r - 在什么情况下我需要使用 R 的 data.table 中的“复制”?
- sql - 是否有可能根据动态打开的引用游标的输出创建视图或表?
- c - 如果需要清理另一个线程中的所有内容,如何在 winapi 中使用关闭处理程序?
- html - 我似乎无法让背景图像在 css 中呈现任何内容
- arrays - 从杂乱的字符串中提取名称
- python - 使用带有自定义清理方法的 CreateView/ModelForm 时在 django 中进行模型验证
- java - 为什么剩余人数计算不正确?