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

