【问题标题】:How do I compare a time value to all the time values in a column in pandas?如何将时间值与熊猫列中的所有时间值进行比较?
【发布时间】:2023-03-22 22:00:02
【问题描述】:

我想对数据框中的列应用条件。该列具有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”实例之间不支持“>”

当我这样做时-

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

【问题讨论】:

    标签: python pandas datetime timedelta


    【解决方案1】:

    您可以比较Timedeltato_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'))
    

    【讨论】:

    • 这给了我 - ValueError:只允许前导负号
    • @Pete - 是否可以调查 whcih 值返回错误?
    • 回溯(最近一次调用最后):文件“pandas_libs\tslibs\timedeltas.pyx”,第 264 行,在 pandas._libs.tslibs.timedeltas.array_to_timedelta64 文件“pandas_libs\tslibs\timedeltas.pyx” ,第 315 行,在 pandas._libs.tslibs.timedeltas.parse_timedelta_string ValueError:只允许前导负号。在处理上述异常的过程中,又出现了一个异常: Traceback (most recent call last): File "C:/Users/PycharmProjects/pythonProject4/conditionalformat.py", line 27, in df['Total Time'] = pd.to_timedelta(df['总时间'].astype(str))
    • @Pete - 我要求的不是完全错误,而是哪个值导致了它。如果前 10 行未通过,则更多的侦探调查工作 0 测试?那么前 20 行?...直到找到有问题的值
    • 谢谢我现在明白转换是问题所在。所以我试图将行数增加 10 并检查它。
    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多