Python 提取多个 txt 文件中最大 Y 值并输出到 Excel 表格

本程序读取文件夹中所有 txt 文件,每个 txt 文件包含两列数据,忽略第一行,提取每个文件中 Y 列的最大值及其对应的 X 值,并将结果输出到 Excel 表格。

import os
import pandas as pd

# 定义文件夹路径
folder_path = '文件夹路径'

# 读取文件夹中的 txt 文件
txt_files = [file for file in os.listdir(folder_path) if file.endswith('.txt')]

# 创建空的 DataFrame
data = pd.DataFrame(columns=['File', 'x_max', 'y_max'])

# 逐个读取 txt 文件
for file in txt_files:
    file_path = os.path.join(folder_path, file)
    
    # 从 txt 文件中读取数据
    df = pd.read_csv(file_path, delimiter='\t', skiprows=1, names=['x', 'y'])
    
    # 找到最大值的索引
    max_index = df['y'].idxmax()
    
    # 提取最大值和对应的 x 值
    max_y = df.loc[max_index, 'y']
    max_x = df.loc[max_index, 'x']
    
    # 将最大值和对应 x 值添加到 DataFrame 中
    data = data.append({'File': file, 'x_max': max_x, 'y_max': max_y}, ignore_index=True)

# 将数据保存到 Excel 表格
output_path = '输出文件路径'
data.to_excel(output_path, index=False)

请将代码中的 '文件夹路径' 替换为您要读取 txt 文件的实际文件夹路径,并将 '输出文件路径' 替换为您希望保存 Excel 文件的路径。运行程序后,将会在指定路径下生成一个包含每个文件中 y 的最大值和对应 x 值,并标明文件名的 Excel 表格。

Python 提取多个 txt 文件中最大 Y 值并输出到 Excel 表格

原文地址: https://www.cveoy.top/t/topic/bAUW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录