You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Python Counter统计结果取Top10后用matplotlib绘制柱状图

报错原因

Counter.most_common(10)返回的是由(元素, 计数值)元组组成的列表,不再是原本继承自字典的Counter对象,自然不存在keys()、values()方法,所以触发了属性不存在的报错。

正确实现方法

你可以直接拆分most_common返回的列表,提取出横纵坐标的参数再绘图,示例代码如下:

# 统计得到top10的元素与计数列表
w_top10 = Counter(twt['mentions'].sum()).most_common(10)
# 拆分出标签(横坐标)和计数(纵坐标)
x_labels, y_counts = zip(*w_top10)
# 绘图
plt.bar(x_labels, y_counts)

如果后续你还需要用到全量的统计结果,也可以先保留完整的Counter对象,再单独提取前10项绘图:

# 先完成全量统计
w = Counter(twt['mentions'].sum())
# 提取top10的坐标参数
top10 = w.most_common(10)
x_labels = [item[0] for item in top10]
y_counts = [item[1] for item in top10]
# 绘图
plt.bar(x_labels, y_counts)

内容的提问来源于stack exchange,提问作者user16918100

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:27:03