使用Pandas Groupby生成客户消费总额直方图的问题
解决方法
你的代码里plot.hist没有加括号,这只是引用方法对象,并未实际调用绘图逻辑,所以无法生成直方图。按以下步骤修改即可:
- 先将客户终身消费总额的计算结果存入变量,提升代码可读性:
customer_lifetime_gross = merged_df.gross.groupby(merged_df['customer_id']).sum()
- 调用
hist()方法绘制基础直方图:
customer_lifetime_gross.plot.hist()
- 若需自定义直方图样式(比如区间数量、标题、轴标签),可添加参数调整:
customer_lifetime_gross.plot.hist( bins=15, title='客户终身消费总额分布', xlabel='消费总额', ylabel='客户数量' )
- 也可以直接使用matplotlib原生方法绘制,灵活性更高:
import matplotlib.pyplot as plt plt.hist(customer_lifetime_gross, bins=15) plt.title('客户终身消费总额分布') plt.xlabel('消费总额') plt.ylabel('客户数量') plt.show()
内容的提问来源于stack exchange,提问作者Ants
相关产品推荐
相关产品推荐

