【发布时间】:2019-01-24 14:25:28
【问题描述】:
我在数据框 old_df 中有一个 Excel 文件,我通过从另一个 Excel 文件数据框 new_df 添加新内容来保持数据最新。如果新数据框中的日期之一在旧数据框中不存在,我只需 pd.concat 将新数据帧和旧数据帧放在一起。
目前此文件中的一些重要列是:
Pub Date Forecast Time Forecast Date State Temp
2018-12-12 23:00:00 2018-12-20 AK 3
2018-12-12 02:00:00 2018-12-20 AK 3.2
2018-12-12 05:00:00 2018-12-20 AK 2.9
.
.
我想确保在使用新数据更新此旧文件时传递重复的行 - 使用 Forecast Time、Forecast Date 和 State 跳过 Pub Date 的非唯一实例。
现在我正在使用一种非常糟糕的方法来处理新旧的Pub Dates 列表:
dateList_old = date_old.tolist()
dateList_new = date_new.tolist()
result = any(elm in dateList_new for elm in dateList_old)
if result == True:
print('One or more of the dates already exists in the database')
sys.exit()
else:
frames = [old_df,new_df]
result = pd.concat(frames)
result.to_excel("file", encoding="utf-8", index=False)
但这会遇到问题,因为假设我要添加相同的 Pub Date 任何类型 - 它会退出整个写入。
我想这样做,如果Pub Date + Forecast Time + Forecast Date + State 在old_df 中,则跳过并继续写入所有其他不存在的行并退出只有当所有这些组合都已经存在时 >.
有没有简单的方法可以做到这一点?
【问题讨论】:
标签: python python-3.x pandas dataframe if-statement