You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在含字符串与datetime格式的列使用.apply()遇类型错误的问询

问题原因分析

你碰到的这个报错核心原因很直接:你的自定义函数里没先过滤掉字符串类型的'null',直接拿它和datetime.timedelta类型的5分钟阈值做大小比较了——字符串和时间差类型根本不支持<这类比较运算符,自然就抛出TypeError了。

解决方法

只需要在自定义函数里先判断元素是否为字符串'null',处理完这个情况后,再对时间差类型的元素做比较逻辑:

import pandas as pd

# 自定义分类函数
def get_time_category(val):
    # 先处理'null'字符串的情况
    if val == 'null':
        return 'N/A'
    # 定义5分钟的时间差阈值
    five_min_threshold = pd.Timedelta(minutes=5)
    # 对时间差类型的元素做比较
    if val < five_min_threshold:
        return 'Momentary'
    else:
        return 'Sustained'

# 应用到DataFrame列上
df['Time_Category'] = df['Elapsed_time'].apply(get_time_category)
额外提醒

如果你的数据里还有其他非timedelta也非'null'的异常值,还可以加一层类型判断来避免报错,比如:

def get_time_category(val):
    if val == 'null':
        return 'N/A'
    # 先确认是timedelta类型再比较
    if isinstance(val, pd.Timedelta) or isinstance(val, datetime.timedelta):
        five_min_threshold = pd.Timedelta(minutes=5)
        return 'Momentary' if val < five_min_threshold else 'Sustained'
    # 处理其他异常类型
    return 'Unknown'

内容的提问来源于stack exchange,提问作者1337nerd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:50:26