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

Pandas代码始终返回False求助:DataFrame流派列批量更新失败

问题描述

尝试遍历DataFrame的行,若原始Genre列中出现对应流派,就将对应流派列的False值更新为True。但运行代码后所有结果均为False,代码如下:

genre_list = ['Action', 'Adventure', 'Sci-Fi','Mystery','Horror','Thriller','Animation','Comedy','Family','Fantasy', 'Drama','Music','Biography','Romance','History','Crime','Western','War','Musical','Sport']

for genres in df.Genre:
  df[genres] = False
for index, row in df.iterrows():
  Genre = str(row['Genre']).split(', ')
for genres in Genre:
  if genre in genres:
    df.at[index, genre] = True

运行结果示例(部分):

Rank                   Title                  Genre  
995   996    Secret in Their Eyes    Crime,Drama,Mystery   
996   997         Hostel: Part II                 Horror   
997   998  Step Up 2: The Streets    Drama,Music,Romance   
998   999            Search Party       Adventure,Comedy   
999  1000              Nine Lives  Comedy,Family,Fantasy 

     Runtime (Minutes)  Rating  Votes  ...  Adventure,Biography  
995                111     6.2  27585  ...                False   
996                 94     5.5  73152  ...                False   
997                 98     6.2  70699  ...                False   
998                 93     5.6   4881  ...                False   
999                 87     5.3  12435  ...                False   
错误分析
  1. 列创建逻辑错误:第一个循环遍历df.Genre的完整流派字符串(比如"Crime,Drama,Mystery"),并以此为列名创建列,完全偏离了genre_list中单个流派列的需求。
  2. 循环缩进错误:后两个循环未嵌套在iterrows()循环内,导致仅处理DataFrame的最后一行,核心更新逻辑完全失效。
  3. 变量未定义:if genre in genres中的genre变量从未声明,属于语法错误(能运行可能是环境残留变量干扰)。
修正后的代码
genre_list = ['Action', 'Adventure', 'Sci-Fi','Mystery','Horror','Thriller','Animation','Comedy','Family','Fantasy', 'Drama','Music','Biography','Romance','History','Crime','Western','War','Musical','Sport']

# 1. 基于genre_list创建所有单个流派列,初始值设为False
for genre in genre_list:
    df[genre] = False

# 2. 遍历每一行,更新对应流派列的值
for index, row in df.iterrows():
    # 拆分当前行的Genre字符串为单个流派列表
    split_genres = str(row['Genre']).split(', ')
    # 遍历每个拆分后的流派,将对应列设为True
    for g in split_genres:
        # 过滤无效流派值(确保在目标列表内)
        if g in genre_list:
            df.at[index, g] = True
更高效的替代方案(避免循环)

iterrows()处理大数据效率较低,推荐用pandas内置的str.get_dummies一键实现流派拆分与列生成:

# 拆分Genre列生成哑变量(0/1),再转为布尔值
genre_dummies = df['Genre'].str.get_dummies(', ').astype(bool)
# 将流派列合并回原DataFrame
df = pd.concat([df, genre_dummies], axis=1)

该方法代码简洁,处理大规模数据时速度远优于循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:37:36