首页 > 解决方案 > 修复多记录表中的错误日期

问题描述

我有一个数据框,其中记录了包含开始日期和结束日期的参与数据。有时会有不好的日期,如下所示:

+--------+------------+-----------+
|   ID   | Start_Date | End_Date  |
+--------+------------+-----------+
| ABC123 | 1/2/2018   | 6/1/2020  |
| ABC123 | 5/1/2027   | 12/2/2017 |
| ABC123 | 1/1/2015   | 4/5/2017  |
+--------+------------+-----------+

是否有脚本可以将错误的开始日期替换为先前记录的结束日期,使其如下表所示

+--------+------------+-----------+
|   ID   | Start_Date | End_Date  |
+--------+------------+-----------+
| ABC123 | 1/2/2018   | 6/1/2020  |
| ABC123 | 4/5/2017   | 12/2/2017 |
| ABC123 | 1/1/2015   | 4/5/2017  |
+--------+------------+-----------+

标签: pythonpandas

解决方案


Arc89,我觉得写自己的函数会更容易。看看这个:

def get_correct_dates(row):
    """ this function checks if start date is past the end date, if yes it takes the previous date"""
    if pd.isna(row["prev_End_Date"]):
        return row["Start_Date"]

    if row["Start_Date"] > row["End_Date"]:
        return row["prev_End_Date"]
    else:
        return row["End_Date"]


df["prev_End_Date"] = df.groupby("ID")["End_Date"].shift(-1)
df["Start_Date"] = df.apply(lambda row: get_correct_dates(row), axis=1)
df.drop("prev_End_Date", axis=1, inplace=True)

推荐阅读