我的数据框 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
.
.
我想确保在使用新数据更新此旧文件时忽略重复行 - 跳过 Pub Date
和 Forecast Time
的非唯一实例,预测日期
和状态
。
现在,我正在使用一种非常糟糕的方法,通过获取新旧版本的 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
- 它会退出整个写入。
我想这样做,以便如果发布日期+预测时间+预测日期+状态
位于old_df
中,则跳过并继续写入所有其他不存在的行不存在并仅当所有这些组合都已存在时退出。
有没有简单的方法可以做到这一点?
最佳答案
您还可以使用:
df.append(df1,ignore_index=True).drop_duplicates(subset=['Pub Date','Forecast Time','Forecast Date','State'])
将两个数据帧视为:
df
:
Pub Date Forecast Time Forecast Date State Temp
0 2018-12-12 23:00:00 2018-12-20 AK 3.0
1 2018-12-12 02:00:00 2018-12-20 AK 3.2
2 2018-12-12 05:00:00 2018-12-20 AK 2.9
df1
:
Pub Date Forecast Time Forecast Date State Temp
0 2018-12-12 23:00:00 2018-12-20 AK 3.0
1 2018-12-13 02:00:00 2018-12-20 AK 3.2
2 2018-12-13 05:00:00 2018-12-20 AK 2.9
df.append(df1,ignore_index=True).drop_duplicates(subset=['Pub Date','Forecast Time','Forecast Date','State'])
Pub Date Forecast Time Forecast Date State Temp
0 2018-12-12 23:00:00 2018-12-20 AK 3.0
1 2018-12-12 02:00:00 2018-12-20 AK 3.2
2 2018-12-12 05:00:00 2018-12-20 AK 2.9
4 2018-12-13 02:00:00 2018-12-20 AK 3.2
5 2018-12-13 05:00:00 2018-12-20 AK 2.9
基本上仅根据某些列附加数据帧并删除重复项,即['Pub Date','Forecast Time','Forecast Date','State']
关于python - 用于更新数据帧 Python 中现有数据的检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348871/