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 文件,并判断第四列是否存在。如果不存在,则跳过处理当前文件;否则,将指定列的数据提取出来。提取的数据存储在 col1
、col2
、col3
和 col4
中,分别表示第一、二、三和四列的数据。
接下来,通过 sorted_indices
得到按照第四列进行排序后的索引数组,根据这个数组重新排列 col1
、col2
、col3
和 col4
的数据。
最后,使用 pd.DataFrame()
将重新排列的数据合并成新的数据框,并通过 df_sorted.to_excel()
将修改后的数据保存到原文件中。每次处理完一个文件,都会在控制台输出该文件名以及处理完成的字样。
等处理完所有的 Excel 文件后,控制台会输出 已完成批量处理
。