Pandas DataFrame 为Date列5位年月值补0生成标准6位日期格式
Date列格式修正实现方案
前置注意
执行前需将Date列转换为字符串类型,否则调用字符串处理方法会报错。
方案1:匹配你初始思路的np.where实现
完整可运行代码:
import numpy as np # 转换Date列为字符串 df['Date'] = df['Date'].astype(str) # 按长度判断补0 df['Date'] = np.where( df['Date'].str.len() == 5, df['Date'].str[:4] + '0' + df['Date'].str[4:], df['Date'] )
逻辑说明:长度为5的日期(即4位年份+1位月份),在第4位(年份结束位置)插入0;长度为6的10-12月日期直接保留原值。
方案2:更简洁的通用写法
无需判断长度,直接对月份部分补位到2位,适配性更强:
# 转换Date列为字符串 df['Date'] = df['Date'].astype(str) # 前4位为年份,剩余月份部分统一补为2位长度 df['Date'] = df['Date'].str[:4] + df['Date'].str[4:].str.zfill(2)
执行上述任意方案后,输出结果完全符合预期格式。
内容的提问来源于stack exchange,提问作者tj judge
相关产品推荐
相关产品推荐

