我有两个数据帧,两个数据帧都包含一个不规则间隔的毫秒分辨率时间戳列.我的目标是匹配行,以便对于每个匹配的行,1)第一个时间戳总是小于或等于第二个时间戳,2)匹配的时间戳对于满足1)的所有时间戳对最接近.
有没有办法用pandas.merge做到这一点?
我想在三列上合并两个数据框:电子邮件、主题和时间戳。数据帧之间的时间戳不同,因此我需要为一组电子邮件和主题确定最匹配的时间戳。
下面是一个可重现的示例,使用为此问题建议的最接近匹配函数。
import numpy as np
import pandas as pd
from pandas.io.parsers import StringIO
def find_closest_date(timepoint, time_series, add_time_delta_column=True):
# takes a pd.Timestamp() instance and a pd.Series with dates in it
# calcs the delta between `timepoint` and each date in `time_series`
# returns the closest date and optionally the number of days in its time delta
deltas = np.abs(time_series - timepoint)
idx_closest_date = np.argmin(deltas)
res = {"closest_date": time_series.ix[idx_closest_date]}
idx = ['closest_date']
if add_time_delta_column:
res["closest_delta"] = deltas[idx_closest_date]
idx.append('closest_delta')
return …Run Code Online (Sandbox Code Playgroud)