在R中按月份分组逐行计算客户支持与客户的响应比率
实现方案(Python Pandas)
核心思路
- 先按月份做数据透视,拆分出两个分组各自的月度Total值
- 按规则计算单月响应率后,关联回原始数据集,保证同月份记录的响应率一致
- 基于单月响应率计算全局平均值
代码实现
首先导入依赖并构造示例数据(实际使用时替换为你自己的df即可):
import pandas as pd # 示例数据构造,可替换为你的真实数据读取逻辑 data = { "Group": ["Customer", "Customer Support", "Customer", "Customer Support", "Customer", "Customer Support", "Customer", "Customer Support"], "Month": ["Jan", "Jan", "Feb", "Feb", "Mar", "Mar", "Apr", "Apr"], "Total": [170, 141, 134, 131, 162, 136, 236, 190] } df = pd.DataFrame(data)
数据处理逻辑:
# 计算每个月的响应率 monthly_ratio = df.pivot(index="Month", columns="Group", values="Total") monthly_ratio["Response Ratio"] = (monthly_ratio["Customer Support"] / monthly_ratio["Customer"]).round(2) # 匹配回原数据集,得到带响应率的结果表 result_df = df.merge(monthly_ratio[["Response Ratio"]], on="Month", how="left") # 计算全局平均响应率 global_avg_ratio = monthly_ratio["Response Ratio"].mean()
结果验证
输出result_df即可得到你预期的格式:
| Group | Month | Total | Response Ratio |
|---|---|---|---|
| Customer | Jan | 170 | 0.82 |
| Customer Support | Jan | 141 | 0.82 |
| Customer | Feb | 134 | 0.97 |
| Customer Support | Feb | 131 | 0.97 |
| Customer | Mar | 162 | 0.83 |
| Customer Support | Mar | 136 | 0.83 |
| Customer | Apr | 236 | 0.80 |
| Customer Support | Apr | 190 | 0.80 |
global_avg_ratio即为所有月份的全局平均响应率。
内容的提问来源于stack exchange,提问作者Dinho
相关产品推荐
相关产品推荐

