将每个Excel文件的数据量统一减少至120000行

为了将每个Excel文件的数据量统一减少至120000行,可以使用Python的pandas库来加载、修改和保存每个文件。以下是一个简单的Python脚本:

首先,确保已经安装了pandas库,如果没有安装,可以通过以下命令安装:

py 复制代码
pip install pandas

接下来是处理数据的代码:

python 复制代码
import os
import pandas as pd

def trim_excel_files(root_dir, max_rows=120000-1):
    # 遍历根目录下的所有子目录
    for condition_dir in os.listdir(root_dir):
        condition_path = os.path.join(root_dir, condition_dir)
        if os.path.isdir(condition_path):
            # 遍历每个工况目录下的所有Excel文件
            for file in os.listdir(condition_path):
                if file.endswith('.xlsx'):
                    file_path = os.path.join(condition_path, file)
                    # 读取Excel文件
                    df = pd.read_excel(file_path)
                    # 如果行数超过120000,进行缩减
                    if len(df) > max_rows:
                        df = df.iloc[:max_rows]
                    # 保存修改后的数据到原文件
                    df.to_excel(file_path, index=False)
                    print(f"Processed {file_path}")

# 指定数据所在的根目录
root_dir = './程序代码1/data'
trim_excel_files(root_dir)

这个脚本首先定义了一个trim_excel_files函数,它接收一个包含数据文件的根目录作为参数。该函数将遍历根目录下的所有子目录,读取每个.xlsx文件,检查其中的行数,如果超过120000行,则将其缩减至120000行,并将修改后的数据保存回原文件。这个过程会替换掉原有的文件,请确保有备份或是可以接受这种替换。

相关推荐
cup111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi003 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵5 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf5 小时前
Agent 流程编排
后端·python·agent
copyer_xyf6 小时前
Agent RAG
后端·python·agent
copyer_xyf6 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf6 小时前
Agent 记忆管理
后端·python·agent
星云穿梭21 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏