【发布时间】:2021-02-19 17:02:26
【问题描述】:
您好,我需要将一些时间序列数据与最近的时间戳对齐,所以我认为 pandas.merge_asof 可能是一个不错的选择。但是,它没有像标准merge 方法中那样设置how='outer' 的选项。
一个例子可以是:
df1:
Value1
Time
2020-07-17 14:25:03.535906075 108
2020-07-17 14:25:05.457247019 110
2020-07-17 14:25:07.467777014 126
df2:
Value2
Time
2020-07-17 14:25:03.535018921 222
2020-07-17 14:25:04.545104980 150
2020-07-17 14:25:07.476825953 60
然后例如,这样做merge_asof:
pd.merge_asof(df1, df2, left_index=True, right_index=True, direction='nearest', tolerance=pd.Timedelta('0.3s'))
结果将是:
Value1 Value2
Time
2020-07-17 14:25:03.535906075 108 222.0
2020-07-17 14:25:05.457247019 110 NaN
2020-07-17 14:25:07.467777014 126 60.0
但我想要的是:
Value1 Value2
Time
2020-07-17 14:25:03.535906075 108 222.0
2020-07-17 14:25:04.545104980 NaN 150.0 <---- this is the difference
2020-07-17 14:25:05.457247019 110 NaN
2020-07-17 14:25:07.467777014 126 60.0
基本上就像一个完整的外连接。
有什么建议吗?提前致谢。
编辑:
所以这是 2 个数据帧的情况。例如,如果有 10 个数据帧(即df1, df2, ..., df10)需要进行这种“最近”合并,该怎么办?
【问题讨论】:
标签: python pandas dataframe merge outer-join