Python-按时间间隔合并数据(R data.table模拟吗?)

时间:2019-03-03 15:49:56

标签: python date time data.table time-series

我正在学习python,并且有一个关于按时间集成数据帧的问题。例如,假设我有2个单独的数据帧,它们具有不规则的时间间隔,但按study_id分组。我想加入彼此相差2小时以内的行。

以前,我为此使用R中的data.table包。下面是此代码的示例。

df_new <- df1[df2, on="Study_ID", allow.cartesian=T][difftime(`date_df1`, `date_df2`, units="hours") <= 2 & difftime(`date_df1`, `date_df2`, units="hours") >= - 2] 

然后,此代码绑定每个实例,其中每个数据框的日期均在每个实例的2小时之内。我想看看是否有类似的python代码?理想情况下,我想合并这些行,以便找到在两次测量之前或之后两个小时之内进行的两次测量之间的最大值。

有什么想法吗?谢谢!

编辑:数据框示例

    ID   Date           HeartRate
    1    4/1/2019 04:13     56
    1    4/2/2019 05:30     45
    1    4/3/2019 22:10     61
    2    4/3/2019 23:13     62
    2    4/5/2019 15:10     67

    df2
    ID   Date             Weight
     1    4/1/2019 06:10     112
     1    4/2/2019 02:30     114
     1    4/3/2019 21:10     112.5
     2    4/3/2019 23:10     113
     2    4/4/2019 00:00     114

    Output (this is what I would love!)
    ID   Date(blood pressure)  HeartRate   Date(weight)   Weight
    1    4/1/2019 4:13            56       4/1/2019 06:10   112
    1    4/3/2019 22:10           61       4/3/2019 21:10   112.5
    2    4/3/2019 23:13           62       4/3/2019 23:10   113
    2    4/3/2019 23:13           62       4/4/2019 00:00   114

在此示例中,每个日期框架中的第二行都被删除了,因为这些度量值在2小时之内不成对。但是df1中显示的倒数第二行会重复,因为df2中有2个案例在2小时之内。

1 个答案:

答案 0 :(得分:0)

首先,您需要将日期保存为日期时间,然后可以执行与data.table中类似的操作,在两个数据框之间执行联接,然后过滤时间差小于tan的记录两个小时。

# store as datetime
df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])

# join dataframes
merged = df1.merge(df2, left_on='ID', right_on='ID', 
                   suffixes=('(blood pressure)', '(weight)'))     
# calculate hour difference between the two dates
hour_dif = np.abs(merged['Date(blood pressure)'] - merged['Date(weight)'])/np.timedelta64(1, 'h')
merged[hour_dif < 2]

哪个产量

#    ID Date(blood pressure)  HeartRate        Date(weight)  Weight
# 0   1  2019-04-01 04:13:00         56 2019-04-01 06:10:00   112.0
# 8   1  2019-04-03 22:10:00         61 2019-04-03 21:10:00   112.5
# 9   2  2019-04-03 23:13:00         62 2019-04-03 23:10:00   113.0