Python新手求助:按空白行分割实验数据为多列多列表的方法
按空白行拆分多组实验数据的解决方案
方法一:纯Python手动读取(新手友好,无额外依赖)
直接逐行读取文件,遇到空白行就完成当前组的收集,拆分列数据后存入列表,逻辑清晰容易理解:
# 打开数据文件(替换成你的实际文件名) with open('data.txt', 'r') as f: groups = [] current_group = [] for line in f: stripped_line = line.strip() # 跳过空行和注释行 if not stripped_line or stripped_line.startswith('#'): # 当前组有数据时,保存并重置 if current_group: groups.append(current_group) current_group = [] continue # 拆分数据并转为数值类型 t, x = map(float, stripped_line.split()) current_group.append((t, x)) # 处理文件末尾未被空行收尾的最后一组数据 if current_group: groups.append(current_group) # 拆分各组的t和x数据 t_groups = [] x_groups = [] for group in groups: t = [item[0] for item in group] x = [item[1] for item in group] t_groups.append(t) x_groups.append(x) # 如果需要单独命名变量(比如t1、t2),可以用动态赋值 # for idx, (t, x) in enumerate(zip(t_groups, x_groups), 1): # locals()[f't{idx}'] = t # locals()[f'x{idx}'] = x # 测试输出 print("第一组t数据:", t_groups[0]) print("第一组x数据:", x_groups[0]) print("第二组t数据:", t_groups[1]) print("第二组x数据:", x_groups[1])
方法二:用Pandas处理(适合已有数据分析流程)
如果日常用Pandas做数据处理,可以通过保留空行再拆分的方式实现,避免数据合并:
import pandas as pd # 读取文件,保留空行,跳过注释行 df = pd.read_csv( 'data.txt', sep='\s+', # 按任意空白字符拆分列 comment='#', # 跳过#开头的注释行 skip_blank_lines=False, # 不跳过空白行 header=None, # 文件无表头(注释行不算表头) names=['t', 'x'] # 自定义列名 ) # 找到所有空白行的索引(对应NaN的行) split_positions = df[df['t'].isna()].index.tolist() # 拆分各组数据 groups = [] start_idx = 0 for pos in split_positions: # 提取当前组并清理空值 group = df.iloc[start_idx:pos].dropna().astype(float) groups.append(group) start_idx = pos + 1 # 处理最后一组 if start_idx < len(df): group = df.iloc[start_idx:].dropna().astype(float) groups.append(group) # 提取各组的t和x列表 t_groups = [g['t'].tolist() for g in groups] x_groups = [g['x'].tolist() for g in groups] # 测试输出 print("第一组t数据:", t_groups[0])
方法三:结合Numpy处理(适合后续绘图计算)
如果需要用Numpy数组做后续绘图或数值计算,可以在手动分组的基础上转成Numpy数组:
import numpy as np # 先按纯Python方法读取分组 with open('data.txt', 'r') as f: groups = [] current_group = [] for line in f: stripped = line.strip() if not stripped or stripped.startswith('#'): if current_group: groups.append(current_group) current_group = [] continue current_group.append(list(map(float, stripped.split()))) if current_group: groups.append(current_group) # 转成Numpy数组 t_arrays = [np.array([row[0] for row in g]) for g in groups] x_arrays = [np.array([row[1] for row in g]) for g in groups] # 测试输出 print("第一组t数组:", t_arrays[0])
内容的提问来源于stack exchange,提问作者Gallo
相关产品推荐
相关产品推荐

