如何拆分工作日数据并根据工作日计算下一个临近日期
问题解决方案
1. 合并工作日拆分行数据
输入数据
| id | workings_days(day of the week) |
|---|---|
| 1 | "1,5" |
| 2 | "2,3" |
目标输出
| id | workings_days(day of the week) |
|---|---|
| 1 | 1 |
| 1 | 5 |
| 2 | 2 |
| 2 | 3 |
代码实现(Python Pandas)
import pandas as pd # 构造输入数据框 input_df = pd.DataFrame({ "id": [1, 2], "workings_days(day of the week)": ['"1,5"', '"2,3"'] }) # 去除引号并拆分工作日字段,再展开为多行 input_df["workings_days(day of the week)"] = input_df["workings_days(day of the week)"].str.strip('"') output_df = input_df.assign( day=input_df["workings_days(day of the week)"].str.split(",") ).explode("day").drop(columns="workings_days(day of the week)") # 重命名列并转换类型 output_df = output_df.rename(columns={"day": "workings_days(day of the week)"}).astype({"workings_days(day of the week)": int}) print(output_df)
2. 计算下一个临近工作日
需求说明
基于拆分后的工作日列表,从当前星期几(1=周一,7=周日)出发,找到最近的下一个工作日。
示例:当前日期为3(周三),工作日为[1,5],则下一个工作日是5(周五)。
代码实现
def find_next_workday(current_day, workdays): sorted_workdays = sorted(workdays) # 从当前日期的下一天开始循环查找,最多循环7天 for offset in range(1, 8): candidate_day = current_day + offset if candidate_day > 7: candidate_day -= 7 if candidate_day in sorted_workdays: return candidate_day return None # 兜底返回,实际不会触发 # 示例调用 current = 3 target_workdays = [1,5] print(find_next_workday(current, target_workdays)) # 输出: 5
内容的提问来源于stack exchange,提问作者Anirban Mukherjee
相关产品推荐
相关产品推荐

