如何基于df_text最新数据更新df_excel对应日期列的状态?
问题需求
现有两个DataFrame:df_text与df_excel,需实现以下逻辑:
- 提取
df_text中end列的最新日期(示例为2023-02-12) - 匹配
df_excel中的对应日期列 - 将
df_text中该最新日期对应Name的status写入df_excel的对应单元格
示例数据
df_text
Name start end status 0 N1 2023-02-08 02:01:45 2023-02-08 08:15:01 completed 1 N2 2023-02-09 06:04:25 2023-02-09 10:35:50 completed 2 N1 2023-02-09 06:04:25 2023-02-09 10:35:50 completed 3 N1 2023-02-10 13:46:01 2023-02-10 16:35:50 completed 4 N4 2023-02-10 16:35:25 2023-02-10 19:35:50 started 5 N1 2023-02-11 16:35:25 2023-02-11 19:35:50 completed 6 N3 2023-02-11 16:35:25 2023-02-11 19:35:50 completed 7 N2 2023-02-11 16:35:25 2023-02-11 19:35:50 started 8 N4 2023-02-12 18:54:03 2023-02-12 23:53:09 completed
df_excel
Unnamed: 0 2023-02-08 00:00:00 2023-02-09 00:00:00 ... 2023-02-12 00:00:00 2023-02-13 00:00:00 2023-02-14 00:00:00 0 N1 Completed Completed ... Waiting Waiting Waiting 1 N2 Waiting Completed ... Waiting Waiting Waiting 2 N3 Waiting Waiting ... Waiting Waiting Waiting 3 N4 Waiting Waiting ... Waiting Waiting Waiting 4 N5 Waiting Waiting ... Waiting Waiting Waiting
示例中,df_text最新end日期为2023-02-12,对应Name为N4,status为completed,需将df_excel中N4行的2023-02-12列单元格从Waiting改为completed。
用户已编写基础读取脚本:
import os import pandas as pd import openpyxl import time df_text = pd.read_csv('data/text.txt', sep='|', skiprows=(0, 2,)).iloc[:, 1:].applymap(str.strip) df_excel = pd.read_excel('data/excel.xlsx', skiprows=1) print(df_excel)
完整实现脚本
以下是实现需求的完整代码,每一步都有注释说明:
import pandas as pd # 读取数据(保留用户原有读取逻辑) df_text = pd.read_csv('data/text.txt', sep='|', skiprows=(0, 2)).iloc[:, 1:].applymap(str.strip) df_excel = pd.read_excel('data/excel.xlsx', skiprows=1) # 1. 处理df_text的日期,提取最新日期 # 将end列转为datetime类型,方便日期比较 df_text['end'] = pd.to_datetime(df_text['end']) # 提取日期部分(去掉时分秒),并找到最大的日期 latest_date = df_text['end'].dt.date.max() # 转换为和df_excel列名一致的格式(带00:00:00的datetime) latest_date_col = pd.to_datetime(latest_date) # 2. 筛选最新日期对应的所有记录 latest_records = df_text[df_text['end'].dt.date == latest_date] # 3. 设置df_excel的索引为Name列,方便按Name定位 df_excel.set_index('Unnamed: 0', inplace=True) # 4. 遍历最新记录,更新df_excel对应单元格 for _, row in latest_records.iterrows(): name = row['Name'] status = row['status'] # 确保Name存在于df_excel的索引中,避免报错 if name in df_excel.index and latest_date_col in df_excel.columns: # 更新单元格,注意status首字母大写对齐原表格格式 df_excel.at[name, latest_date_col] = status.capitalize() # 5. 将更新后的df_excel保存回文件(覆盖原文件或保存为新文件) df_excel.to_excel('data/updated_excel.xlsx') print("更新完成,已保存为updated_excel.xlsx")
关键说明
- 日期格式统一:将
df_text的end列转为datetime类型,提取日期部分后再转为和df_excel列名一致的datetime格式,确保匹配准确 - 多记录处理:如果同一天有多个Name的状态更新,脚本会自动处理所有对应行
- 容错处理:添加了Name和日期列存在性检查,避免因数据缺失导致报错
- 格式对齐:将
status首字母大写,和df_excel原表格的Completed/Waiting格式保持一致
内容的提问来源于stack exchange,提问作者RedRum
相关产品推荐
相关产品推荐

