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

使用条件语句向列表追加DataFrame列值触发KeyError如何解决

问题原因

  • 列名不匹配:你定义的DataFrame实际列名为review_rating、review_text,代码中错误使用了不存在的reviews.rating、reviews.text作为列名,直接触发KeyError。
  • 逻辑写法错误:你写的for column in df[['列1','列2']]是遍历列名,完全不符合逐行判断取值的需求;同时if df[df['reviews.rating']] <= 2.0的布尔索引写法不符合pandas语法规则,就算改对列名也无法正常运行。

正确实现方案

方案1:逐行遍历实现(对应你原本想写的循环逻辑)

import pandas as pd
df = pd.DataFrame({'product':['shoe','shirt','pants','socks'],
                   'review_rating':[1.2,3.0,4.0,2.1],
                   'review_text':['good','bad','good','bad']})
good_reviews = []
# 逐行遍历df
for idx, row in df.iterrows():
    # 条件判断:review_rating小于等于2.0的话追加对应review_text
    if row['review_rating'] <= 2.0:
        good_reviews.append(row['review_text'])

print(good_reviews) # 输出结果为 ['good']

方案2:pandas向量化操作(更简洁高效的写法,不需要手动写循环)

直接用布尔索引筛选符合条件的行,再把对应列转成列表即可:

good_reviews = df.loc[df['review_rating'] <= 2.0, 'review_text'].tolist()
print(good_reviews) # 输出结果同样为 ['good']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:15:04