Python按时间间隔(R)合并数据数据表模仿?)

2024-04-23 14:09:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,有一个关于按时间集成数据帧的问题。例如,假设我有两个独立的数据帧,时间间隔不规则,但按研究id分组。我希望将两个小时内的行连接起来。你知道吗

以前,我用过数据表用R包装。下面是这个代码的一个例子。你知道吗

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代码?理想情况下,我希望合并这些行,以便可以找到在测量之前或之后2小时内出现的测量之间的最大值。你知道吗

有什么想法吗?谢谢您!你知道吗

编辑:数据帧示例

    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小时内。你知道吗


Tags: 数据实例代码iddate时间df1units
2条回答

首先您需要将日期保存为datetime,然后您可以执行类似于在data.table中所做的操作,在两个数据帧之间执行连接,然后过滤时差小于两小时的记录。你知道吗

# 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

我要感谢@josemz给了我一个非常好的答案!它确实起到了作用,我列出的一长串问题是由于数据清理错误而产生的问题。非常感谢你的帮助!你知道吗

相关问题 更多 >