我有两个数据框:
第一个日期范围是:
import pandas as pd
df1 = pd.DataFrame({'serialNo':['aaaa','bbbb','cccc','ffff','aaaa','bbbb','aaaa'],
'Name':['Sayonti','Ruchi','Tony','Gowtam','Toffee','Tom','Sayonti'],
'testName': [4402, 3747 ,5555,8754,1234,9876,3602],
'moduleName': ['singing', 'dance','booze', 'vocals','drama','paint','singing'],
'endResult': ['WARNING', 'FAILED', 'WARNING', 'FAILED','WARNING','FAILED','WARNING'],
'Date':['2018-10-5','2018-10-6','2018-10-7','2018-10-8','2018-10-9','2018-10-10','2018-10-8'],
'Time_df1':['23:26:39','22:50:31','22:15:28','21:40:19','21:04:15','20:29:11','19:54:03']})
第二个数据帧是:
df2 = pd.DataFrame({'serialNo':['aaaa','bbbb','aaaa','ffff','xyzy','aaaa'],
'Food':['Strawberry','Coke','Pepsi','Nuts','Apple','Candy'],
'Work': ['AP', 'TC','OD', 'PU','NO','PM'],
'Date':['2018-10-1','2018-10-6','2018-10-2','2018-10-3','2018-10-5','2018-10-10'],
'Time_df2':['09:00:00','10:00:00','11:00:00','12:00:00','13:00:00','14:00:00']
})
我要根据序列号加入两者:
df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])
result = pd.merge(df1,df2,on=['serialNo'],how='inner')
现在,我希望Date_y位于Date_x的3天内(从Date_x开始) 这意味着Date_X +(1、2、3天)应为Date_y。我可以通过以下方式获得该信息,但我还想检查我不知道如何实现的时间范围
result = result[result.Date_x.sub(result.Date_y).dt.days.between(0,3)]
我想检查时间,以使Time_df2在开始时间为Time_df1的6小时内。请帮忙吗?
答案 0 :(得分:0)
您可能在数据框中有一个合并日期和时间的列。这是在数据框中合并一行的示例:
GRANT EXECUTE
然后给定两个datetime对象,您可以简单地减去以找到所需的差异:
# Combining Date_x and time_df1
value_1_x = datetime.datetime.combine(result['Date_x'][0].date() ,\
datetime.datetime.strptime(result['Time_df1'][0], '%H:%M:%S').time())
# Combining date_y and time_df2
value_2_y = datetime.datetime.combine(result['Date_y'][0].date() , \
datetime.datetime.strptime(result['Time_df2'][0], '%H:%M:%S').time())
哪个给出输出:
difference = value_1_x - value_2_y
print(difference)
我的理解是,您希望查看是否在3天6个小时(或总共78个小时)之内。您可以轻松地将其转换为小时,然后进行所需的比较:
4 days, 14:26:39
哪个给出输出:
hours_difference = abs(value_1_x - value_2_y).total_seconds() / 3600.0
print(hours_difference)
希望有帮助!