Pandas分箱报错:TypeError: 'int'与'str'实例间不支持'<'运算
问题分析与解决
错误TypeError: '<' not supported between instances of 'int' and 'str'的核心原因是你的Per Student Budget列存储的是字符串类型,而pd.cut需要基于数值进行区间比较,字符串和整数无法直接比较才导致报错。
你之前修改labels或spending_bins类型的思路不对,正确解决步骤如下:
转换目标列的数值类型
如果该列带有$等非数值字符,先清理再转换:# 去掉$符号并转为浮点型 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)重新运行分箱代码
类型转换完成后,原代码即可正常执行: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
相关产品推荐
相关产品推荐

