使用NumPy处理数组 提取字符串数值将年月转为总月数
年月字符串转总月数实现方案
核心逻辑是从字符串中分别提取年、月对应的数值,按照「年数*12 + 月数」计算总月数,用正则匹配做提取可以同时兼容「仅标注年」「同时标注年和月」两种格式,对单复数、空格差异的容错性更高。
针对给出的numpy数组场景,直接运行以下代码即可得到预期结果:
import numpy as np import re YrsAndMonths = np.array(['6 Years and 12 Months','7 Years and 8 Months','2 Years']) Months = [] for item in YrsAndMonths: # 提取年数值:匹配Years/Year前的整数 year_res = re.search(r'(\d+)\s*Years?', item) year = int(year_res.group(1)) if year_res else 0 # 提取月数值:匹配Months/Month前的整数,无匹配则记为0 month_res = re.search(r'(\d+)\s*Months?', item) month = int(month_res.group(1)) if month_res else 0 # 计算总月数,转字符串匹配要求的输出格式 total_months = str(year * 12 + month) Months.append(total_months)
运行后Months的输出为['84', '92', '24'],和预期结果完全一致。
补充说明
- 正则规则里加了
s?匹配,可以兼容"1 Year"、"1 Month"这类单数表述,不会因为单复数差异匹配失败 - 如果后续需要做数值统计、计算,去掉
str()转换直接存整数即可 - 如果是用pandas读取CSV处理整列数据,可以用
apply批量转换,参考代码:
import pandas as pd import re def to_total_months(text): text = str(text) year_res = re.search(r'(\d+)\s*Years?', text) year = int(year_res.group(1)) if year_res else 0 month_res = re.search(r'(\d+)\s*Months?', text) month = int(month_res.group(1)) if month_res else 0 return year * 12 + month # 假设df为CSV读入的DataFrame,'duration'为存储年月字符串的列名 df['total_months'] = df['duration'].apply(to_total_months)
内容的提问来源于stack exchange,提问作者user19443053
相关产品推荐
相关产品推荐

