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

Python中如何按年月排序DataFrame并绘制月度趋势折线图

解决方案

步骤1:将月份列转为有序分类类型

首先定义标准的月份顺序,把月份列从普通字符串转为pandas有序分类类型,后续排序、绘图都会自动遵循指定的时间顺序

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 定义1-12月对应的英文缩写顺序
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# 转换month列为有序分类类型
df10['month'] = pd.Categorical(df10['month'], categories=month_order, ordered=True)

步骤2:按年份、月份排序

此时再调用sort_values就会按照时间逻辑排序,不会出现字母序错乱的问题

df10_sorted = df10.sort_values(by=['year', 'month'], ignore_index=True)

步骤3:绘制正确顺序的折线图

根据你的数据场景二选一即可:

  • 如果是单年数据,直接用月份作为x轴即可
plt.figure(figsize=(12,6))
sns.lineplot(x='month', y='Sales', data=df10_sorted, marker='o')
plt.title('月度销售额变化趋势')
plt.xlabel('月份')
plt.ylabel('销售额')
plt.grid(True)
plt.show()
  • 如果是多年数据,建议拼接为完整年月作为x轴,避免不同年份的相同月份重叠
# 拼接生成年月字符串字段
df10_sorted['year_month'] = df10_sorted['year'].astype(str) + '-' + df10_sorted['month'].astype(str)
plt.figure(figsize=(16,6))
sns.lineplot(x='year_month', y='Sales', data=df10_sorted, marker='o')
plt.title('跨年度月度销售额变化趋势')
plt.xlabel('年月')
plt.ylabel('销售额')
plt.xticks(rotation=45)
plt.grid(True)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:09:07