解决Python程序报错KeyError: nan:处理缺失值找到最大值
非常抱歉给您带来困扰。出现这个错误的原因是由于存在缺失值(NaN)导致无法索引。为了解决这个问题,您可以在找到最大值之前先处理缺失值。以下是修正后的代码:
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'])
# 处理缺失值
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
if not df.empty:
# 找到最大值的索引
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文件的路径。运行程序后,将会在指定路径下生成一个包含每个文件中最大值和对应x值,并标明文件名的Excel表格。
原文地址: http://www.cveoy.top/t/topic/bcIp 著作权归作者所有。请勿转载和采集!