如何用Python对文件中相似行的数据进行平均处理?
数据平滑处理:合并相邻近X值的行并取平均
需求说明
我有一个绘图用的数据文件,因轮廓提取问题导致曲线不够平滑。需要实现:若相邻两行第一列(X值)的相对误差小于0.01%,则将这两行合并为一行,新行的两列分别为原两行对应列的平均值。
初始代码问题
你提供的初始代码存在几个问题:
- 输入数据是空格分隔而非逗号,
split(',')无法正确解析 - 直接遍历
Lines列表无法方便地处理相邻行合并逻辑(合并后需要跳过下一行) - 未实现相对误差计算和合并逻辑
完整实现代码
def smooth_data(input_file, output_file, rel_error_threshold=0.0001): # 读取数据并过滤空行 with open(input_file, 'r') as f: lines = [line.strip() for line in f if line.strip()] processed_data = [] index = 0 total_lines = len(lines) while index < total_lines: # 解析当前行的数值 x_current, y_current = map(float, lines[index].split()) # 检查是否有下一行可比较 if index < total_lines - 1: x_next, y_next = map(float, lines[index+1].split()) # 计算相对误差(处理x_current为0的特殊情况) if x_current != 0: relative_error = abs((x_next - x_current) / x_current) else: # x为0时,直接判断x_next是否接近0 relative_error = 0 if abs(x_next) < 1e-6 else float('inf') # 满足误差阈值则合并两行 if relative_error <= rel_error_threshold: avg_x = (x_current + x_next) / 2 avg_y = (y_current + y_next) / 2 processed_data.append((avg_x, avg_y)) index += 2 # 跳过下一行 continue # 不满足合并条件,直接添加当前行 processed_data.append((x_current, y_current)) index += 1 # 将处理后的数据写入文件 with open(output_file, 'w') as f: for x, y in processed_data: # 格式化输出,保持数值可读性 f.write(f"{x}\t{y}\n") # 调用示例:替换为你的输入输出文件名 smooth_data('input.txt', 'output.txt')
代码关键点说明
- 使用
with open上下文管理器处理文件,自动关闭文件,避免资源泄漏 - 过滤空行,防止解析空内容报错
- 处理X值为0的特殊情况(避免除以0的错误)
- 采用
while循环遍历,方便合并后跳过下一行 - 可通过调整
rel_error_threshold参数修改误差阈值(0.0001对应0.01%)
输入输出示例
输入示例
0 0 1 10 2 19 2.001 22 3 29 3.001 31.1 4 40 5 50 6 60
输出示例
0 0 1 10 2.0005 20.5 3.0005 30.05 4 40 5 50 6 60
注:输出中的X值为精确平均值,若需要简化为整数(如你示例中的2、3),可在格式化时添加
round()函数,例如f"{round(x, 0)}\t{y}\n"
内容的提问来源于stack exchange,提问作者Martin7
相关产品推荐
相关产品推荐

