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

Pandas列表追加操作异常:comb列表仅生成1个索引的问题排查求助

Pandas列表追加操作异常:comb列表仅生成1个索引的问题排查求助

我在文件夹里有两个CSV文件,每个循环迭代的输出是avg_mtf。之前在glob的其他循环里,我成功创建列表并完成了拼接,但这次的comb列表却只生成了1个索引,实在找不到问题出在哪,求帮忙看看!

我的代码如下:

import pandas as pd
import glob

file_list=glob.glob('*.csv')
print (file_list);

for file in file_list:
    data=pd.read_csv(file,encoding='cp1252', index_col=False, header=None)
    
    indices=data[(data[0].str.contains('Results=3DTiltCorrMTF@Best'))&(data[0].str.contains('Tangential'))]
    # dataframe with all rows containing Tangential
    a=indices.index.values
    tan_data=[]
    sag_data=[]
    comb x_axis=[]  # 这里存在语法错误!
    
    n=a[0]+1
    n=data.loc[n]
    x=n.str.split(r':| ', expand=True)
    x=x.iloc[:,1:-1]
    x=x.T.reset_index(drop=True)
    x=x.iloc[1:,:]
    x=x.reset_index(drop=True)
    del n
    
    for i in a:
        n=data.loc[i+2]
        n=n.str.split(' ', expand=True)
        n=n.iloc[:,1:-1]
        tan_mtf=n.T
        tan_data.append(tan_mtf)
    tan_mtf=pd.concat(tan_data,axis=1,ignore_index=True)
    tan_mtf=tan_mtf.reset_index(drop= True)
    del i,n,a
    
    indices=data[(data[0].str.contains('Results=3DTiltCorrMTF@Best'))&(data[0].str.contains('Sagittal'))]
    a=indices.index.values
    
    for i in a:
        n=data.loc[i+2]
        n=n.str.split(' ', expand=True)
        n=n.iloc[:,1:-1]
        sag_mtf=n.T
        sag_data.append(sag_mtf)
    sag_mtf=pd.concat(sag_data,axis=1,ignore_index=True)
    sag_mtf=sag_mtf.reset_index(drop= True)
    
    tan_mtf=tan_mtf.astype(float)
    sag_mtf=sag_mtf.astype(float)
    avg_mtf=(tan_mtf+sag_mtf)/2
    comb.append(avg_mtf)

问题排查与修正方案

我帮你梳理下几个核心问题点,这些大概率是导致comb列表只有1个元素的原因:

1. 致命语法+作用域错误:comb初始化位置错误

代码里的comb x_axis=[]是明显的语法错误,应该拆成comb = []和x_axis = []两个独立的初始化语句。更关键的是:你把comb的初始化放在了for file in file_list:的循环内部!

这意味着每次处理一个CSV文件时,comb都会被重置为空列表,最后循环结束后,comb里只会保留最后一个CSV文件的avg_mtf,自然只有1个索引。

修正:把comb的初始化移到外层循环之前,确保所有CSV文件的结果都追加到同一个列表:

file_list=glob.glob('*.csv')
print (file_list)
# 把初始化移到循环外,避免每次循环重置
comb = []
x_axis = []

for file in file_list:
    # 后续处理代码...

2. 转义字符错误:&需替换为&

代码里的&是HTML转义字符,在Python中逻辑与运算符应该用&,虽然可能是复制时的格式问题,但运行时会直接导致语法报错,记得替换。

3. 优化后的完整代码

我帮你整理了修正后的代码,同时去掉了一些冗余的del语句,让逻辑更清晰:

import pandas as pd
import glob

file_list = glob.glob('*.csv')
print(file_list)

# 初始化全局列表,避免循环内重置
comb = []
x_axis = []

for file in file_list:
    data = pd.read_csv(file, encoding='cp1252', index_col=False, header=None)
    
    # ---------------------- 处理Tangential MTF ----------------------
    indices = data[(data[0].str.contains('Results=3DTiltCorrMTF@Best')) & 
                   (data[0].str.contains('Tangential'))]
    a = indices.index.values
    tan_data = []
    
    for i in a:
        n = data.loc[i+2]
        n = n.str.split(' ', expand=True)
        n = n.iloc[:,1:-1]
        tan_mtf = n.T
        tan_data.append(tan_mtf)
    
    tan_mtf = pd.concat(tan_data, axis=1, ignore_index=True)
    tan_mtf = tan_mtf.reset_index(drop=True)
    
    # ---------------------- 处理Sagittal MTF ----------------------
    indices = data[(data[0].str.contains('Results=3DTiltCorrMTF@Best')) & 
                   (data[0].str.contains('Sagittal'))]
    a = indices.index.values
    sag_data = []
    
    for i in a:
        n = data.loc[i+2]
        n = n.str.split(' ', expand=True)
        n = n.iloc[:,1:-1]
        sag_mtf = n.T
        sag_data.append(sag_mtf)
    
    sag_mtf = pd.concat(sag_data, axis=1, ignore_index=True)
    sag_mtf = sag_mtf.reset_index(drop=True)
    
    # ---------------------- 计算平均并追加到comb ----------------------
    tan_mtf = tan_mtf.astype(float)
    sag_mtf = sag_mtf.astype(float)
    avg_mtf = (tan_mtf + sag_mtf) / 2
    comb.append(avg_mtf)

# 可选:把所有avg_mtf拼接成一个大的DataFrame
final_combined_mtf = pd.concat(comb, axis=1, ignore_index=True)
# 验证列表长度
print(f"comb列表的元素数量:{len(comb)}")
print(f"最终拼接后的DataFrame形状:{final_combined_mtf.shape}")

4. 验证方法

运行修正后的代码后,通过print(len(comb))查看列表长度,如果输出为2(对应两个CSV文件),就说明问题解决了。如果还是有异常,可以检查每个CSV文件的avg_mtf是否正确生成,比如打印avg_mtf.shape确认维度是否符合预期。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:50:27