用python怎么实现多个excel自动两列位置对调?

我的文件夹里有多个excel,都是xlsx格式的,我想将每个文件的第二列和第三列都互换,应该怎么写?

import pandas as pd
import os

# 指定一个 Excel 文件夹目录
path = 'E:/下载/文件夹的名称/'
# 遍历文件夹获取所有符合条件的 Excel 文件完整目录
for root, dirs, files in os.walk(path):
# 遍历文件
for file in files:
# 如果有不需要操作的文件另外添加判断条件即可
# 拼接完整目录
filePath = path + file
# 读取数据
df = pd.read_excel(filePath)
# 所有列名
columnName = df.columns.values
# B C 互换位置
columnName[1], columnName[2] = columnName[2], columnName[1]
# 重组 DataFrame
new = df.loc[:, columnName]
# 到这一步已经实现了你的需求,如果另存为
dataFrame = pd.DataFrame(new)
# 覆盖保存,要另存为 filePath 改成 path + file.split('.')[0] + '1.' + file.split('.')[1]
dataFrame.to_excel(filePath, index=False)

追问

运行了,没报错,但打开文件发现两列并没有互换

追答

修改红色代码

温馨提示:答案为网友推荐,仅供参考
相似回答