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

如何在Pandas中替换日期列的西班牙语月份缩写实现日期解析

解决方案

方案1:替换月份缩写后转日期(兼容性最高,无需依赖系统locale,更推荐使用)

  • 第一步:定义西语月份缩写到数字的映射字典
es_month_map = {
    'ene': '01',
    'feb': '02',
    'mar': '03',
    'abr': '04',
    'may': '05',
    'jun': '06',
    'jul': '07',
    'ago': '08',
    'sep': '09',
    'oct': '10',
    'nov': '11',
    'dic': '12'
}
  • 第二步:用正则匹配日期列中的西语月份缩写,替换为对应数字
    不需要匹配整个日期串,仅匹配两个斜杠中间的3位小写字母即可,逻辑更精准:
# 请将代码中的date_col替换为你实际的日期列名
df['date_col'] = df['date_col'].str.replace(
    r'\/([a-z]{3})\/', 
    lambda match: f'/{es_month_map[match.group(1)]}/', 
    regex=True
)
  • 第三步:转换为标准datetime格式
import pandas as pd
df['date_col'] = pd.to_datetime(
    df['date_col'], 
    format='%d/%m/%Y', 
    errors='coerce' # 不合法的日期(比如示例中缺少年份的22/feb/)会转为空值NaT,方便后续清洗
)

方案2:直接指定西语locale转换(仅适合本地环境配置过西语locale的场景)

如果运行环境已经安装了西班牙语locale,可以不用做字符串替换,直接指定格式转换:

import locale
import pandas as pd

# 不同系统的locale参数略有差异,Windows可尝试'es_ES',Linux/macOS可尝试'es_ES.utf-8'
locale.setlocale(locale.LC_TIME, 'es_ES.utf-8')

# %b对应匹配本地语言的月份缩写,直接转换即可
df['date_col'] = pd.to_datetime(
    df['date_col'], 
    format='%d/%b/%Y', 
    errors='coerce'
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:27:02