我有两个数据框left = pd.DataFrame([['A', 10, datetime(2020, 5, 17, 20, 12, 28)],\ ['B', 15, datetime(2020, 5, 17, 16, 22, 45)],\ ['C', 20, datetime(2020, 5, 17, 12, 45, 12)],\ ['D', 25, datetime(2020, 5, 17, 13, 57, 44)]],\ columns = ['Letter_l', 'Int_l', 'Datetime_l'])和right = pd.DataFrame([['A', 20, datetime(2020, 5, 17, 20, 12, 35)],\ ['B', 30, datetime(2020, 5, 17, 18, 45, 25)],\ ['C', 40, datetime(2020, 5, 17, 12, 45, 20)],\ ['D', 50, datetime(2020, 5, 17, 18, 16, 44)]],\ columns = ['Letter_r', 'Int_r', 'Datetime_r'])我想加入三列中的两列:Letter和Datetime。对于日期时间,我不是在寻找精确匹配,而是在寻找正确数据帧的最大差异 10 秒。我知道如何在正常条件下加入:merged_df = pd.merge(left=left, right=right, how='left',\ left_on=['Letter_l'], right_on=['Letter_r'])但我正在寻找的输出是:|-----|--------------|-----------|--------------------|--------------|-----------|--------------------|| | Letter_l | Int_l | datetime_l | Letter_r | Int_r | datetime_r | |-----|--------------|-----------|--------------------|--------------|-----------|--------------------|| 0 | A | 10 | 2020-05-17 20:12:28| A | 20 | 2020-05-17 20:12:35|| 1 | C | 20 | 2020-05-17 12:45:12| C | 40 | 2020-05-17 12:45:20||-----|--------------|-----------|--------------------|--------------|-----------|--------------------|这可以使用标准来完成吗pd.merge?当然我可以尝试使用sqlite3
1 回答
慕神8447489
TA贡献1780条经验 获得超1个赞
使用on执行asof
合并,容差为秒:pd.merge_asof
DateTime
10
df = pd.merge_asof(left.sort_values('Datetime_l'),
right.sort_values('Datetime_r'),
left_by='Letter_l', right_by='Letter_r',
left_on='Datetime_l', right_on='Datetime_r',
direction='nearest', tolerance=pd.Timedelta(seconds=10))\
.dropna(subset=['Letter_r'])
结果:
Letter_l Int_l Datetime_l Letter_r Int_r Datetime_r
0 C 20 2020-05-17 12:45:12 C 40.0 2020-05-17 12:45:20
3 A 10 2020-05-17 20:12:28 A 20.0 2020-05-17 20:12:35
添加回答
举报
0/150
提交
取消