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

Python Pandas二次循环仅插入单个字符的问题及修复

问题修复:循环中变量名冲突导致trial-type列被拆分为单个字符

你遇到的核心问题是变量名冲突:
你最初定义了列表condition=["circle", "emot", "neut", "square"],但在循环中使用了for condition in condition:,这会把原本的列表变量覆盖成循环中的单个字符串元素。第一次被试循环结束后,condition已经变成了最后一个元素square;后续处理其他被试时,for condition in condition:会遍历字符串square的每个字符,导致trial-type列只能显示单个字符。

修复后的代码

AFNI_data_location = "C:\\Users\\jes6785\\Box\\Almeida_Lab\\BITREC\\BEHAVIORAL_FILES_CLEANED_JULY_2023\\"
BIDS_output_location = "C:\\Users\\jes6785\\Box\\Almeida_Lab\\BITREC\\BIDS\\"
# 原列表变量重命名为conditions,避免冲突
conditions = ["circle", "emot", "neut", "square"] 
# 子目录列表变量重命名为subj_list,提升可读性
subj_list = os.listdir(AFNI_data_location) 

# 遍历每个被试目录
for subj in subj_list:
    print(subj)
    subj_only = subj.split("-")[0] 
    session = subj.split("-")[1]
    filedir = os.path.join(AFNI_data_location, subj)
    participant_time = pd.DataFrame(columns=['onset', 'duration', 'trial-type'])
    run = "2"
    # 循环变量改用cond,不和原列表变量冲突
    for cond in conditions:                        
        file = glob.glob(os.path.join(filedir, '*run' + run + '*' + cond + '*.txt'))
        for file in file:
            print(file)
            data = pd.read_csv(file, sep = " ", header = None) 
            data = data.T
            data.columns = ["onset"]
            data.insert(1, "duration", run)
            # 使用cond赋值trial-type,保证是完整条件字符串
            data.insert(2, "trial-type", cond)
            participant_time = pd.concat([participant_time, data], ignore_index = True)
        participant_time = participant_time.sort_values('onset')
       
    participant_time.to_csv(
        os.path.join(BIDS_output_location, f"sub-{subj_only}_ses-0{session}_task-cpt-{run}_events.tsv"), 
        index=False, 
        sep="\t"
    )

关键修改点

  1. 将原列表变量condition重命名为conditions,彻底避免和循环变量的命名冲突
  2. 循环变量改用cond,确保每次遍历的都是conditions列表中的完整字符串元素
  3. 把subj = os.listdir(...)改为subj_list,循环变量保留subj,提升代码可读性的同时避免潜在的变量覆盖问题

修改后,每个被试循环时都会正常遍历完整的条件列表,trial-type列将正确显示完整的条件名称,不会再出现单个字符的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:17:32