如何在pandas DataFrame中将月份名称列转换为两位月份数字
问题解决方案
strptime() argument 1 must be str, not Series报错是因为Python原生的datetime.strptime仅支持传入单个字符串参数,无法直接处理pandas Series类型的整列数据,需要用pandas的向量化操作实现需求。
方案1:内置时间转换方法(通用场景推荐)
直接用pd.to_datetime解析整列月份缩写,再提取两位月份即可:
import pandas as pd # 假设存储月份缩写的列名为 month_abbr # format参数中 %b 对应英文缩写月份(Jan/Feb/Mar等) # dt.strftime('%m') 输出带前导零的两位月份字符串 df['month_num'] = pd.to_datetime(df['month_abbr'], format='%b').dt.strftime('%m') # 如果需要输出1-12的整数类型月份,替换为以下代码即可 # df['month_num'] = pd.to_datetime(df['month_abbr'], format='%b').dt.month
如果系统默认locale不是英文导致解析失败,可以先手动指定时间locale:
import locale locale.setlocale(locale.LC_TIME, 'en_US.UTF-8')
方案2:字典映射(大数据量场景推荐)
月份缩写是固定枚举值,直接用映射表转换速度更快,也方便兼容特殊自定义缩写:
month_map = { 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12' } df['month_num'] = df['month_abbr'].map(month_map)
内容的提问来源于stack exchange,提问作者Elle Li
相关产品推荐
相关产品推荐

