Python Pandas: 批量 Excel 数据归一化处理
以下是一个示例代码,可以实现将一个文件夹中的所有excel文件进行数据归一化,并将结果保存到原始文件中:
import os
import pandas as pd
# 定义归一化函数
def normalize_dataframe(df):
# 对每一列进行归一化处理
for col in df.columns:
df[col] = (df[col] - df[col].min()) / (df[col].max() - df[col].min())
return df
# 定义文件夹路径和文件扩展名
folder_path = 'path/to/folder'
file_extension = '.xlsx'
# 遍历文件夹中的所有excel文件
for filename in os.listdir(folder_path):
if filename.endswith(file_extension):
# 读取excel文件
file_path = os.path.join(folder_path, filename)
df = pd.read_excel(file_path)
# 进行归一化处理
df_normalized = normalize_dataframe(df)
# 将归一化后的数据保存回原始文件
with pd.ExcelWriter(file_path, engine='openpyxl', mode='a') as writer:
df_normalized.to_excel(writer, sheet_name='normalized', index=False)
这段代码会遍历指定文件夹中的所有扩展名为.xlsx的excel文件,读取每个文件的数据,对每列进行归一化处理,然后将结果保存回原始文件的一个名为'normalized'的sheet中。注意,保存时使用的是openpyxl引擎,并且使用了'a'模式,以便在原始文件的末尾添加新的sheet。如果原始文件中已经有名为'normalized'的sheet,那么这段代码会在其后面添加新的数据。
原文地址: https://www.cveoy.top/t/topic/oqXe 著作权归作者所有。请勿转载和采集!