如何将时间值与pandas中一列中的所有时间值进行比较?

2024-06-16 12:32:30 发布

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

我想对数据帧中的列应用一个条件。该列具有格式为HH:MM:SS的时间值,我想将其与固定时间值(阈值)进行比较,但我得到了错误。将阈值转换为datetime.datetime.strptime会产生错误。我想问的是——为了比较任意两个时间值,我应该如何存储它们,或者我应该将它们转换成什么,以便进行比较?阈值为字符串格式,列值为datetime.time格式

当我这样做的时候-

threshold = datetime.datetime.strptime('1:04:00','%H:%M:%S').time()  
df_styled = df.style.apply(lambda x:['background:red' if x > threshold else "background:white" for x in df['Total Time']], axis=0) 

我得到-

TypeError: '>' not supported between instances of 'datetime.datetime' and 'datetime.time'

当我这样做的时候-

threshold = datetime.datetime.strptime('1:04:00','%H:%M:%S')
df['Total Time'] = df['Total Time'].apply(lambda x: datetime.datetime.strptime(x,'%H:%M:%S'))
df_styled = df.style.apply(lambda x:['background:red' if x > threshold else 'background:white' for x in df['Total Time']], axis=0)

我得到了错误

TypeError: strptime() argument 1 must be str, not datetime.time


Tags: lambdadfdatetimethresholdtime格式错误时间
1条回答
网友
1楼 · 发布于 2024-06-16 12:32:30

您可以比较由^{}^{}创建的时间增量:

threshold = pd.Timedelta('1:04:00')
df['Total Time'] = pd.to_timedelta(df['Total Time'].astype(str))

df_styled = df.style.apply(lambda x:['background:red' if x > threshold else "background:white" for x in df['Total Time']], axis=0) 

编辑:问题数据的解决方案:

df['Total Time'] = pd.to_timedelta(pd.to_datetime(df['Total Time'].astype(str)).dt.strftime('%H:%M:%S'))

相关问题 更多 >