如何按Content_ID_group列列表长度迭代展开pandas DataFrame指定行
问题排查与解法
你的代码存在以下错误:
- 列名拼写错误:原始数据列名为
Content Id_group,你的代码中写为Content ID_group,大小写不匹配会导致无法正确读取列数据。 - 判断逻辑错误:你在判断值类型时永远取第0行
graph['Content ID_group'][0],没有和当前循环的第g行绑定,导致所有行的判断逻辑都和第0行一致,逻辑完全错误。 - 未处理目标列取值:你直接追加整行数据,没有把列表里的单个元素替换到
Content Id_group列,输出结果不符合需求。 append操作使用错误:pandas的append方法不是原地操作,直接调用g_whole.append(itt)不会修改g_whole本身,必须赋值回变量才能保存结果,这是你运行后g_whole一直为空的核心原因。- int类型分支逻辑错误:当值为int时你直接追加单个值,而非整行数据,会导致DataFrame结构混乱。
推荐最优解法
pandas提供了原生的explode方法,专门用于将列表类型的列拆分为多行,其他列值自动复用,完全符合你的需求,一行代码即可实现:
import pandas as pd # 原始DataFrame graph = pd.DataFrame({"Event Name": ["ord", "inflow"], "Media":["google", "appier"], "Content Id_group":[[1,2,3,4,5,6], 0]}) # 拆分列表列,保留原索引和你需要的输出完全一致 result = graph.explode('Content Id_group') print(result)
运行后输出:
Event Name Media Content Id_group 0 ord google 1 0 ord google 2 0 ord google 3 0 ord google 4 0 ord google 5 0 ord google 6 1 inflow appier 0
修复后的循环实现(仅作参考,更推荐使用explode方法)
g_whole = [] for g in range(len(graph)): current_row = graph.loc[g] content_val = current_row['Content Id_group'] # 判断当前行的Content Id_group类型 if isinstance(content_val, list): # 遍历列表每个元素生成新行 for item in content_val: new_row = current_row.copy() new_row['Content Id_group'] = item g_whole.append(new_row) else: # 非列表类型直接保留原行 g_whole.append(current_row) # 一次性转换为DataFrame,性能远高于循环中反复append DataFrame g_whole = pd.DataFrame(g_whole) print(g_whole)
内容的提问来源于stack exchange,提问作者goodrain
相关产品推荐
相关产品推荐

