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

遍历pandas DataFrame的两种方式:为何结果正确却被判错误?

Pandas项目代码结果一致但评估错误的原因分析

我正在进行一个简短的Pandas项目,尽管我的代码生成的列表与提供的正确代码结果一致,但项目评估始终判定该任务错误。请问我的代码是否存在问题,只是在当前DataFrame下恰好得到相同结果?

我的代码

# Define an empty list
colors = []

# Iterate over rows of netflix_movies_col_subset
for t in netflix_movies_col_subset['genre']:
    if t == 'Children' :
        colors.append('red')
    elif t == 'Documentaries' :
        colors.append('blue')
    elif t == 'Stand-up' :
        colors.append('green')
    else:
        colors.append('black')
        
# Inspect the first 10 values in your list        
print(colors[:10])

提供的正确代码

# Define an empty list
colors = []

# Iterate over rows of netflix_movies_col_subset
for lab, row in netflix_movies_col_subset.iterrows():
    if row['genre'] == 'Children' :
        colors.append('red')
    elif row['genre'] == 'Documentaries' :
        colors.append('blue')
    elif row['genre'] == 'Stand-up' :
        colors.append('green')
    else:
        colors.append('black')
        
# Inspect the first 10 values in your list        
print(colors[0:10])

问题分析

  • 当前结果一致的原因:在默认连续整数索引的DataFrame中,直接遍历genre列的Series值,顺序和iterrows()遍历行的顺序完全一致,所以生成的colors列表内容和顺序都相同。

  • 你的代码存在的潜在问题:

    1. 索引匹配风险:如果DataFrame的行索引被修改过(比如删除部分行、手动设置非连续索引),遍历Series的顺序依然是数据存储的物理顺序,但iterrows()会严格按照DataFrame显示的行顺序(含索引)遍历。此时若后续逻辑依赖colors列表元素与原DataFrame行的索引对应关系,你的代码会出现匹配错误。
    2. 不符合任务预期:项目评估大概率是希望你掌握iterrows()这种Pandas标准的逐行遍历方法,你的实现虽然结果正确,但没有贴合题目要求的技术路径,因此被判定错误。
    3. 扩展性差:如果后续需要用到当前行的其他列数据,你的方法需要额外从DataFrame中按索引取值,而iterrows()直接提供了整行数据,更便于扩展逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:21:05