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

Python Pandas如何根据自定义年份规则将列值前6位转换为日期

实现代码及思路

核心逻辑

  • 提取VAL列的前6位字符,拆分出年、月、日三个片段
  • 根据VAL首字符是否为0,按规则计算完整年份
  • 拼接为YYYY-MM-DD格式的字符串,写入新列date

方法1:向量化操作(性能更优,适合大数据量)

import pandas as pd

# 构造示例DataFrame,可替换为你的实际数据源
df = pd.DataFrame({
    'VAL': ['99050605188', '00102255789', '20042388956', '02111505667']
})

# 提取日期相关片段
date_part = df['VAL'].str[:6]
yy = date_part.str[:2].astype(int)
mm = date_part.str[2:4]
dd = date_part.str[4:6]

# 按规则计算年份
year = pd.Series(
    [2000 + y if val.startswith('0') else 1900 + y 
     for y, val in zip(yy, df['VAL'])],
    index=df.index
)

# 拼接得到目标date列
df['date'] = year.astype(str) + '-' + mm + '-' + dd

方法2:自定义函数+apply(逻辑更直观,适合小数据量)

import pandas as pd

df = pd.DataFrame({
    'VAL': ['99050605188', '00102255789', '20042388956', '02111505667']
})

def convert_val_to_date(val):
    front6 = val[:6]
    yy = int(front6[:2])
    mm = front6[2:4]
    dd = front6[4:6]
    full_year = 2000 + yy if val.startswith('0') else 1900 + yy
    return f"{full_year}-{mm}-{dd}"

df['date'] = df['VAL'].apply(convert_val_to_date)

输出结果验证

执行代码后输出df,结果和预期完全一致:

VAL        date
0  99050605188  1999-05-06
1  00102255789  2000-10-22
2  20042388956  1920-04-23
3  02111505667  2002-11-15

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:06:05