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

在Pandas中按月份统计名称数量并绘制有序柱状图的问题

解决方法

1. 修正统计逻辑,保证月份有序

你之前的代码按统计数量排序导致月份顺序混乱,正确做法是按月份时间顺序排序,而非数量。直接对分组后的结果按索引(即月份)排序即可:

import pandas as pd

# 可选:若time列是字符串类型,转成datetime更利于时间排序
df['time'] = pd.to_datetime(df['time'])

# 按月份分组统计名称数量,并按时间顺序排序
monthly_counts = df.groupby('time').size().sort_index()

此时monthly_counts的索引是有序的月份,值为对应月份的名称总数,两者天然一一对应,无需单独提取x轴数据。

2. 绘制柱状图

提供两种简单的绘图方式:

方式一:pandas 直接绘图

import matplotlib.pyplot as plt

monthly_counts.plot(
    kind='bar',
    xlabel='月份',
    ylabel='名称数量',
    title='每月名称数量统计'
)
plt.xticks(rotation=45)  # 旋转x轴标签,避免重叠
plt.tight_layout()  # 自动调整布局,防止标签被截断
plt.show()

方式二:matplotlib 手动绘图

import matplotlib.pyplot as plt

# 若time是datetime类型,用strftime转成友好的字符串格式显示
plt.bar(monthly_counts.index.strftime('%Y-%m'), monthly_counts.values)
plt.xlabel('月份')
plt.ylabel('名称数量')
plt.title('每月名称数量统计')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

问题原因说明

你之前的y=df.groupby('time').size().sort_values(ascending=True)是按统计数量排序,打乱了月份的原始时间顺序;而x=df.time.unique()是原数据中月份的出现顺序,两者顺序不匹配,因此无法正确关联。通过按索引(月份)排序,就能保证x轴和y轴数据完全对应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:45:32