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

Python运行循环报TypeError: bitwise_and不支持输入类型如何解决

报错原因
  • 运算符优先级错误:Python中按位与运算符&的优先级高于所有比较运算符,你写的df.iloc[i,8] >= 80 & df.iloc[i,8] <90会优先计算80 & df.iloc[i,8],如果第8列是浮点型数据,就会触发按位运算不支持浮点类型的报错。逻辑判断场景请使用逻辑与运算符and,如果坚持使用&,需要给每个比较条件单独加小括号包裹。
  • 循环范围越界:range(0,df.shape[0]+1)的上限设置错误,DataFrame行索引取值范围为0 ~ df.shape[0]-1,你设置的上限会导致最后一次循环访问不存在的行,触发索引越界错误。
修正方案

方案1:直接修改原有循环逻辑

for i in range(df.shape[0]):
    score = df.iloc[i,8]
    if score >= 90:
        df.iloc[i,9] = "Ex"
    elif score >= 80 and score < 90:
        df.iloc[i,9] = "A"
    elif score >= 70 and score < 80:
        df.iloc[i,9] = "B"
    elif score >= 60 and score < 70:
        df.iloc[i,9] = "C"
    elif score >= 50 and score < 60:
        df.iloc[i,9] = "D"
    else:
        df.iloc[i,9] = "E"

方案2:使用Pandas向量化操作(更高效,无需循环)

针对Pandas数据处理场景,更推荐使用内置的cut函数完成分段打标,执行效率远高于手动循环:

import pandas as pd

# 定义分数分段区间和对应等级标签
bins = [0, 50, 60, 70, 80, 90, float('inf')]
labels = ['E', 'D', 'C', 'B', 'A', 'Ex']

# 直接批量计算结果赋值给第9列
df.iloc[:,9] = pd.cut(df.iloc[:,8], bins=bins, labels=labels, right=False)

内容的提问来源于stack exchange,提问作者Ankit Kumar Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:15:00