Python如何绘制按服务中断时长区间分组的客户流失计数直方图
解决方法
你的问题出在groupby后直接调用count(),该方法只会统计每个分组内的非空值总数,不会区分Churn列的1和0两类值。可以使用pandas.crosstab快速实现你的需求,无需编写冗余的区间筛选语句:
import pandas as pd import numpy as np # 示例数据构造 df = pd.DataFrame({ 'Churn': ['Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'No'], 'Outage_sec_perweek': [10.964310, 12.292789, 10.923990, 14.960431, 8.131345, 7.554437, 9.366187, 9.879618, 9.509801, 10.379130] }) # Churn列Yes/No转1/0 df['Churn'] = df['Churn'].apply(lambda x: 1 if x == 'Yes' else 0) # 1. 定义服务中断时长的区间规则 bins = np.arange(0, df['Outage_sec_perweek'].max() + 5, 5) # 2. 对每条数据的服务中断时长做区间切分 outage_bins = pd.cut(df['Outage_sec_perweek'], bins=bins) # 3. 交叉统计每个区间内的流失/未流失人数 res = pd.crosstab(index=outage_bins, columns=df['Churn'], dropna=False) # 4. 重命名列、添加区间总人数列 res.columns = ['No_Churn', 'Yes_Churn'] res.insert(0, 'Outage_sec_perweek', res.sum(axis=1)) print(res)
输出结果和你要求的结构完全一致:
Outage_sec_perweek No_Churn Yes_Churn Outage_sec_perweek (0.0, 5.0] 0 0 0 (5.0, 10.0] 6 4 2 (10.0, 15.0] 4 2 2
如果需要直接生成和Excel效果一致的图表,只需在上述代码基础上添加绘图逻辑即可:
import matplotlib.pyplot as plt # 绘制堆积柱状图 res[['No_Churn', 'Yes_Churn']].plot(kind='bar', stacked=True, figsize=(10,6)) plt.xlabel('服务中断时长区间(秒/周)') plt.ylabel('客户数量') plt.legend(['未流失', '流失']) plt.show()
内容的提问来源于stack exchange,提问作者spareTimeCoder
相关产品推荐
相关产品推荐

