Python处理时间列:拆分并转换年月为月数计算
拆分时间列并转换为月数计算
问题需求
需要将DataFrame中的Time列拆分为time_in_role(months)和time_in_company(months)两列,并将原始的“年+月”格式转换为以月为单位的总时长。
解决方案代码
import pandas as pd # 初始化数据 data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Time':['3 years 4 months in role 20 years in company', '1 year 7 months in role 2 years 2 months in company', '2 years 1 month in role 7 years 2 months in company', '3 months in role 8 years 2 months in company']} df = pd.DataFrame(data) # 定义转换函数:将年/月字符串转为总月数 def convert_to_months(time_str): total_months = 0 # 提取年数并转换为月 if 'year' in time_str: year_num = int(time_str.split(' year')[0].split()[-1]) total_months += year_num * 12 # 提取月数 if 'month' in time_str: month_num = int(time_str.split(' month')[0].split()[-1]) total_months += month_num return total_months # 拆分Time列为角色时间和公司时间片段 df[['role_time', 'company_time']] = df['Time'].str.split(' in role ', expand=True) # 清理公司时间片段的冗余后缀 df['company_time'] = df['company_time'].str.replace(' in company', '') # 计算两列的总月数 df['time_in_role(months)'] = df['role_time'].apply(convert_to_months) df['time_in_company(months)'] = df['company_time'].apply(convert_to_months) # 移除不需要的中间列(可选操作) df = df.drop(['Time', 'role_time', 'company_time'], axis=1) # 输出结果 print(df)
代码说明
- 转换函数:
convert_to_months函数会识别字符串中的年、月信息,将年数乘以12后与月数相加,得到总月数,兼容仅含年或仅含月的情况。 - 拆分时间列:通过
str.split(' in role ')将原始Time列拆分为角色时长和公司时长两部分,再用str.replace清除公司时长末尾的冗余文本。 - 计算月数:对拆分后的两个时间列分别应用转换函数,生成目标列,最后可选择删除中间过程列,得到干净的结果。
输出结果
执行代码后将得到如下DataFrame:
| Name | time_in_role(months) | time_in_company(months) |
|---|---|---|
| Tom | 40 | 240 |
| nick | 19 | 26 |
| krish | 25 | 86 |
| jack | 3 | 98 |
内容的提问来源于stack exchange,提问作者Sushmitha
相关产品推荐
相关产品推荐

