Python&Pandas使用lambda生成分数对应评论列出现True值问题排查
问题原因
- 三元表达式语法错误
Python三元表达式的结构为返回值A if 判定条件 else 返回值B,你编写的lambda中else后放置的是数值比较表达式,该表达式执行后只会返回布尔值True/False,这就是列中出现True的根本原因。 - 列赋值逻辑覆盖
你四次对df['composition_comment']执行赋值操作,每次都会直接覆盖整列的已有值,仅最后一次的赋值逻辑会被保留。最后一次的逻辑为:分数<=27.96时返回对应评论文本,否则返回element >= 0.04的布尔值(该条件对所有正分数都成立,所以统一返回True),因此只有分数低于28的行输出符合预期,其余行均为True。
修复方案
方案1:单lambda多分支判断(符合你现有写法的修改思路)
把所有分支判断整合到同一个lambda中,避免重复覆盖列值:
df['composition_comment'] = df['composition_score'].apply(lambda element: composition_comment_a_level if element >= composition_score_value * 0.9 else composition_comment_b_level if element >= composition_score_value * 0.8 else composition_comment_c_level if element >= composition_score_value * 0.7 else composition_comment_d_level )
方案2:使用pd.cut实现(更简洁高效的pandas原生分箱方案)
针对这类区间匹配场景,用pd.cut不需要写复杂的分支判断,维护成本更低:
# 定义分箱边界和对应评论标签 bins = [0, composition_score_value*0.7, composition_score_value*0.8, composition_score_value*0.9, composition_score_value] labels = [composition_comment_d_level, composition_comment_c_level, composition_comment_b_level, composition_comment_a_level] # right=False表示区间为左闭右开,匹配你设定的分数区间规则 df['composition_comment'] = pd.cut(df['composition_score'], bins=bins, labels=labels, right=False)
内容的提问来源于stack exchange,提问作者Daniel Hutchinson
相关产品推荐
相关产品推荐

