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

Pandas分箱报错:TypeError: 'int'与'str'实例间不支持'<'运算

问题分析与解决

错误TypeError: '<' not supported between instances of 'int' and 'str'的核心原因是你的Per Student Budget列存储的是字符串类型,而pd.cut需要基于数值进行区间比较,字符串和整数无法直接比较才导致报错。

你之前修改labels或spending_bins类型的思路不对,正确解决步骤如下:

  1. 转换目标列的数值类型
    如果该列带有$等非数值字符,先清理再转换:

    # 去掉$符号并转为浮点型
    school_spending_df["Per Student Budget"] = school_spending_df["Per Student Budget"].str.replace('$', '').astype(float)
    

    如果没有特殊字符,直接转类型即可:

    school_spending_df["Per Student Budget"] = school_spending_df["Per Student Budget"].astype(float)
    
  2. 重新运行分箱代码
    类型转换完成后,原代码即可正常执行:

    spending_bins = [0, 585, 630, 645, 680]
    labels = ["<$585", "$585-630", "$630-645", "$645-680"]
    
    school_spending_df["Spending Ranges (Per Student)"] = pd.cut(
        school_spending_df["Per Student Budget"],
        spending_bins, 
        labels=labels,
        include_lowest=True
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:42:36