[英]Merging two Dataframes in Pandas based on time-range difference
我有這兩個數據幀, df1
, df2
。
df1:
dateTime userId session
2018-08-30 02:20:19 2233 1
2018-08-30 05:32:10 1933 1
2018-08-30 09:10:39 2233 2
2018-08-30 10:26:59 2233 3
2018-08-30 11:56:25 4459 1
2018-08-30 12:30:55 4459 1
df2:
clickTime userId session clickId
2018-08-30 02:21:09 2233 1987
2018-08-30 02:23:19 2233 1988
2018-08-30 02:24:00 2233 1989
2018-08-30 02:32:09 2233 1990
2018-08-30 05:33:10 1933 2009
2018-08-30 05:35:19 1933 2010
2018-08-30 05:36:59 1933 2011
2018-08-30 11:57:25 4459 3012
2018-08-30 11:58:55 4459 3013
我想合並userId
上的兩個數據幀以及時間范圍列,比如在 10 分鍾的范圍內。 的df1
。
所以我想要的數據框是這樣的:
dateTime userId session clickTime clickId
2018-08-30 02:20:19 2233 1 2018-08-30 02:21:09 1987
2018-08-30 02:20:19 2233 1 2018-08-30 02:23:19 1988
2018-08-30 02:20:19 2233 1 2018-08-30 02:21:09 1989
2018-08-30 02:20:19 2233 1 2018-08-30 02:21:09 1990
所以我希望每個用戶都有它們,數據框應該是這樣的,對於每個userId
我想要這個數據框。 是否可以?
所以它就像我想在userId
上合並df1
和df2
以及df2
clickTime
應該位於df1
的dateTime
列的 10-15 分鍾的時間范圍內。
IIUC:使用pandas.merge_asof
pd.merge_asof(
df1, df2,
left_on='dateTime',
right_on='clickTime',
by='userId',
direction='nearest'
)
dateTime userId session clickTime clickId
0 2018-08-30 02:20:19 2233 1 2018-08-30 02:21:09 1987
1 2018-08-30 05:32:10 1933 1 2018-08-30 05:33:10 2009
2 2018-08-30 09:10:39 2233 2 2018-08-30 02:32:09 1990
3 2018-08-30 10:26:59 2233 3 2018-08-30 02:32:09 1990
4 2018-08-30 11:56:25 4459 1 2018-08-30 11:57:25 3012
5 2018-08-30 12:30:55 4459 1 2018-08-30 11:58:55 3013
您可以指定要看多遠的容差
pd.merge_asof(
df1, df2,
left_on='dateTime',
right_on='clickTime',
by='userId',
direction='nearest',
tolerance=pd.Timedelta(15, unit='m')
)
dateTime userId session clickTime clickId
0 2018-08-30 02:20:19 2233 1 2018-08-30 02:21:09 1987.0
1 2018-08-30 05:32:10 1933 1 2018-08-30 05:33:10 2009.0
2 2018-08-30 09:10:39 2233 2 NaT NaN
3 2018-08-30 10:26:59 2233 3 NaT NaN
4 2018-08-30 11:56:25 4459 1 2018-08-30 11:57:25 3012.0
5 2018-08-30 12:30:55 4459 1 NaT NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.