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

如何将DataFrame中M000替换为当月名称、M001替换为下月名称并自动化?

自动化替换DataFrame中Month列的M000/M001为对应月份名称

核心思路

借助datetime和dateutil模块自动获取当前月份及下一个月份的名称,构建映射字典后批量替换DataFrame列值,彻底替代手动修改操作。

代码实现

  1. 导入依赖库
import pandas as pd
from datetime import datetime
from dateutil.relativedelta import relativedelta
  1. 自动获取当月/下月名称
# 获取当前系统日期
today = datetime.today()

# 获取当月英文全称(如"October",需中文可看后续补充)
current_month = today.strftime("%B")
# 获取下月名称,自动处理跨年场景(比如12月的下月是次年1月)
next_month = (today + relativedelta(months=1)).strftime("%B")
  1. 批量替换列值
# 构建M000/M001与月份名称的映射关系
month_map = {"M000": current_month, "M001": next_month}

# 替换Month列的对应值
df["Month"] = df["Month"].map(month_map)

补充:中文月份名称处理

如果需要输出中文月份(如"十月"),需先设置系统本地化环境:

import locale

# Windows系统设置
locale.setlocale(locale.LC_TIME, 'Chinese (Simplified)_China.936')
# Linux/macOS系统设置
# locale.setlocale(locale.LC_TIME, 'zh_CN.UTF-8')

# 此时获取的月份名称为中文格式
current_month = today.strftime("%B")
next_month = (today + relativedelta(months=1)).strftime("%B")

关键说明

  • 使用relativedelta而非timedelta,可以精准处理月份增减,避免跨月/跨年时的计算错误
  • 代码每次运行都会自动读取当前系统日期,完全实现自动化替换,无需手动更新月份值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:35:27