python对多个excel做批量降序处理

import pandas as pd
import os

# 定义需要排序的列
col_to_sort = 3  # 第四列

# 遍历文件夹下的所有Excel文件
for filename in os.listdir(r'C:\Users\win10\Desktop\对conclusion的不同智库词频统计'):
    if filename.endswith('.xlsx'):
        # 打开Excel文件
        file_path = os.path.join(r'C:\Users\win10\Desktop\对conclusion的不同智库词频统计', filename)
        df = pd.read_excel(file_path, engine='openpyxl')
        
        # 判断第四列是否存在
        if df.columns[col_to_sort] not in df.columns:
            print(f'{filename} 文件没有第四列数据,跳过处理')
            continue
        
        # 提取前三列和第四列的数据
        col1 = df.iloc[:, 0].tolist()
        col2 = df.iloc[:, 1].tolist()
        col3 = df.iloc[:, 2].tolist()
        col4 = df.iloc[:, col_to_sort].tolist()
        
        # 按照第四列的降序排列(同时保留前三列数据的对应关系)
        sorted_indices = sorted(range(len(col4)), key=lambda k: col4[k], reverse=True)
        col1 = [col1[i] for i in sorted_indices]
        col2 = [col2[i] for i in sorted_indices]
        col3 = [col3[i] for i in sorted_indices]
        col4 = [col4[i] for i in sorted_indices]
        
        # 将排好序的四列数据合并成新的数据框
        df_sorted = pd.DataFrame({
            df.columns[0]: col1,
            df.columns[1]: col2,
            df.columns[2]: col3,
            df.columns[col_to_sort]: col4
        })
        
        # 保存修改后的Excel文件
        df_sorted.to_excel(file_path, index=False, engine='openpyxl')
        print(f'{filename} 文件处理完成')

print('已完成批量处理')

这段代码是用来对指定文件夹下的所有Excel文件按照第四列数据进行降序排列,并保留前三列和第四列数据的对应关系,并将修改后的数据保存到原文件中。

具体代码解释如下:

首先,通过定义 col_to_sort 来指定需要排序的列,默认是第四列(索引为3),但是也可以根据实际情况进行修改。

然后,使用 os.listdir() 来遍历指定文件夹下的所有文件,通过 filename.endswith('.xlsx') 来筛选出所有后缀为 .xlsx 的文件。

接着,使用 pd.read_excel() 打开 Excel 文件,并判断第四列是否存在。如果不存在,则跳过处理当前文件;否则,将指定列的数据提取出来。提取的数据存储在 col1col2col3col4 中,分别表示第一、二、三和四列的数据。

接下来,通过 sorted_indices 得到按照第四列进行排序后的索引数组,根据这个数组重新排列 col1col2col3col4 的数据。

最后,使用 pd.DataFrame() 将重新排列的数据合并成新的数据框,并通过 df_sorted.to_excel() 将修改后的数据保存到原文件中。每次处理完一个文件,都会在控制台输出该文件名以及处理完成的字样。

等处理完所有的 Excel 文件后,控制台会输出 已完成批量处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值