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

遍历字符串列表向DataFrame追加行却返回空DataFrame的问题

问题排查与修复

问题根源

  • 函数无返回值:原函数没有return语句,调用df = my_function(my_list)后,df实际是None,而非空DataFrame
  • 数据未累积:遍历列表时,每次循环都重新创建data变量,之前的处理结果被直接覆盖,最终仅保留最后一次循环的结果(若最后一次无匹配则为空)
  • 未使用容器收集行数据:没有用列表等容器存储每一行的处理结果,无法将多行数据合并为一个DataFrame

修复后的代码

import pandas as pd
import re

# 假设stopwords是已定义的停用词集合
col_names = ["Version Available", "Newer Version Available"]

def my_function(item):
    rows = []  # 初始化列表存储所有行数据
    for x in item:
        querywords = x.split()
        resultwords = [word for word in querywords if word not in stopwords]
        result = ' '.join(resultwords)
        
        # 提取新版本信息
        line = re.findall(r'\bNewer.*(?=\sVersion\b)', result)
        line = "".join(line).replace("Newer Version Available :", "")
        
        # 提取当前可用版本信息
        line2 = re.findall(r'(Version.*){2}(?=\sSource\b)', result)
        line2 = "".join(line2).replace("Version Available :", "")
        
        # 将当前行数据加入列表(注意列顺序与col_names对应)
        rows.append([line2, line])
    
    # 用所有行数据创建DataFrame并返回
    return pd.DataFrame(rows, columns=col_names)

# 调用函数生成DataFrame
df = my_function(my_list)

修复说明

  1. 新增rows列表,用于累积每一行的处理结果,避免循环中覆盖数据
  2. 函数末尾返回最终生成的DataFrame,确保调用后能获取有效结果
  3. 调整了行数据的顺序,保证与col_names的列顺序一一对应(原代码中列顺序颠倒,会导致数据错位)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:25:31