我想要将一个条件应用于dataframe中的列。该列具有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:“datetime.datetime”和“datetime.time”的实例之间between >不支持
当我这么做的时候-
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()参数1必须是str,而不是datetime.time
发布于 2021-06-17 06:07:40
您可以比较Timedelta和to_timedelta创建的时间差。
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'))https://stackoverflow.com/questions/68013797
复制相似问题