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

如何使用Python将pandas数组内的数值转换为ABCD评分体系

错误原因说明
  • 第一份代码最后错误将grade函数对象直接覆盖为float(total_score),且没有对数组的每个元素调用分级函数,pandas数组无法直接批量转为单个float值
  • 第二份代码未导入bisect库,return语句后的列表推导式永远不会执行,参数传递逻辑错误,也没有适配pandas数组的批量处理规则
正确实现方案

假设total_score是你提到的100×1格式的pandas DataFrame对象。

方案1:使用pandas原生pd.cut(推荐,性能最优)

pandas内置分箱方法,不需要循环遍历,处理效率远高于自定义函数方案:

import pandas as pd

# 定义分箱区间和对应评级,默认左开右闭,刚好匹配你的分级规则
bins = [0, 60, 70, 80, 90, 100]
labels = ['E', 'D', 'C', 'B', 'A']

# 取第一列分数生成分级,结果存在新的grade列中
total_score['grade'] = pd.cut(total_score.iloc[:, 0], bins=bins, labels=labels, include_lowest=True)

方案2:修正自定义函数+apply写法

如果你要保留原有自定义函数的逻辑,用pandas的apply方法批量调用即可:

def grade(score):
    if 91 <= score <= 100:
        return 'A'
    elif 81 <= score <= 90:
        return 'B'
    elif 71 <= score <= 80:
        return 'C'
    elif 61 <= score <= 70:
        return 'D'
    else:
        return 'E'

# 对第一列所有元素应用分级函数
total_score['grade'] = total_score.iloc[:, 0].apply(grade)

方案3:修正bisect版本实现

import bisect

def determine_grade(score):
    breakpoints = [60, 70, 80, 90]
    grades = ['E', 'D', 'C', 'B', 'A']
    i = bisect.bisect_right(breakpoints, score)
    return grades[i]

total_score['grade'] = total_score.iloc[:, 0].apply(determine_grade)

内容的提问来源于stack exchange,提问作者Justin Habel Kiswanto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:39:04