python - 修复多记录表中的错误日期
问题描述
我有一个数据框,其中记录了包含开始日期和结束日期的参与数据。有时会有不好的日期,如下所示:
+--------+------------+-----------+
| 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 |
+--------+------------+-----------+
解决方案
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)
推荐阅读
- ruby - 在 sqlite3 中从数组中戏弄整数值
- context-free-grammar - 识别语言的非确定性 PDA 的状态机
- java - 使用子字符串和循环的特定格式
- sass - sass:“...:”之后的无效 CSS:预期的“}”,是“url('...”)
- android - Android:CardView 广场向新活动显示
- python - 具有像素加权交叉熵的 U-Net:输入维度错误
- python-2.7 - 如何过滤字典
- javascript - Swagger 错误:ptr 必须是 JSON 指针
- python - 执行 sess.run() 时出现“TypeError:'type' 对象不可下标”
- java - 如何从监听器获取数据?