查询一个系统以随机抽取系统的历史状态,时间由
update_time
并将其附加到数据帧
df
.每次提取都会获取特定日期范围的数据,该日期范围可以估计为列的最小值和最大值
timestamp
.最新的获取是在获取数据期间提供系统最可靠的信息。从…起
df
我想删除前一行中存在的所有行
更新时间
最近的一份报告对此进行了报道
更新时间
.
我正在考虑下面的算法,它可以获得预期的结果,但对于大数据帧来说速度非常慢:
import pandas as pd
from datetime import datetime as dt
df = pd.DataFrame({'id':range(10), 'name':['John', 'James', 'Harry', 'Lilia', 'Rachel', 'Harry', 'Lilia', 'Stu', 'Lilia', 'Tom'], 'timestamp':[dt(2022,1,3),dt(2021,12,26),dt(2021,11,13),dt(2021,11,3),dt(2021,10,2),dt(2021,11,13),dt(2021,11,3),dt(2021,10,1),dt(2021,11,3),dt(2021,10,3)], 'update_time':[dt(2022,1,3,0,0,12),dt(2022,1,3,0,0,12),dt(2022,1,3,0,0,12),dt(2022,1,3,0,0,12),dt(2022,1,3,0,0,12),dt(2021,11,15),dt(2021,11,15),dt(2021,11,15),dt(2021,11,10),dt(2021,11,10)]})
update_times = df['update_time'].unique()
update_times.sort()
update_times = np.flip(update_times)
df_output = pd.DataFrame()
for update_time in update_times:
df_temp = df[df['update_time'] == update_time]
df_output = pd.concat([df_output, df_temp], axis=0)
df = df[df['timestamp'] < min(df_output['timestamp'])]
>>> df
id name timestamp update_time
0 0 John 2022-01-03 2022-01-03 00:00:12
1 1 James 2021-12-26 2022-01-03 00:00:12
2 2 Harry 2021-11-13 2022-01-03 00:00:12
3 3 Lilia 2021-11-03 2022-01-03 00:00:12
4 4 Rachel 2021-10-02 2022-01-03 00:00:12
5 5 Harry 2021-11-13 2021-11-15 00:00:00
6 6 Lilia 2021-11-03 2021-11-15 00:00:00
7 7 Stu 2021-10-01 2021-11-15 00:00:00
8 8 Lilia 2021-11-03 2021-11-10 00:00:00
9 9 Tom 2021-10-03 2021-11-10 00:00:00
>>> df_output
id name timestamp update_time
0 0 John 2022-01-03 2022-01-03 00:00:12
1 1 James 2021-12-26 2022-01-03 00:00:12
2 2 Harry 2021-11-13 2022-01-03 00:00:12
3 3 Lilia 2021-11-03 2022-01-03 00:00:12
4 4 Rachel 2021-10-02 2022-01-03 00:00:12
7 7 Stu 2021-10-01 2021-11-15 00:00:00
有什么明智的建议可以更快地完成吗?