Python 批量删除 Excel 文件特定列
使用 Python 和 Pandas 库,可以轻松删除文件夹中所有 Excel 文件的特定列。以下代码示例展示了如何实现这一功能:
import os
import pandas as pd
# 设置要删除的列
columns_to_delete = ['Column1', 'Column2']
# 遍历文件夹中的 Excel 文件
for file in os.listdir('path/to/folder'):
if file.endswith('.xlsx'):
# 读取 Excel 文件
df = pd.read_excel(os.path.join('path/to/folder', file))
# 删除要删除的列
df.drop(columns_to_delete, axis=1, inplace=True)
# 保存修改后的 Excel 文件
df.to_excel(os.path.join('path/to/folder', file), index=False)
在上面的代码中,我们首先设置要删除的列,然后使用 os 库遍历文件夹中的 Excel 文件。对于每个 Excel 文件,我们使用 Pandas 库的 read_excel 函数读取 Excel 文件,然后使用 drop 函数删除要删除的列。最后,我们使用 to_excel 函数将修改后的 DataFrame 保存回 Excel 文件中。
具体步骤:
- 导入库: 导入
os和pandas库。 - 设置要删除的列: 使用列表
columns_to_delete存储要删除的列名。 - 遍历文件夹: 使用
os.listdir()获取文件夹中所有文件名,并通过endswith('.xlsx')筛选出 Excel 文件。 - 读取 Excel 文件: 使用
pd.read_excel()读取每个 Excel 文件到 DataFrame 中。 - 删除列: 使用
df.drop()删除指定的列。 - 保存修改后的文件: 使用
df.to_excel()保存修改后的 DataFrame 到同一个 Excel 文件中。
注意事项:
- 请确保
path/to/folder指向正确的文件夹路径。 index=False表示不保存索引列。
通过以上代码,你可以轻松地批量删除文件夹中所有 Excel 文件的特定列,提高数据处理效率。
原文地址: https://www.cveoy.top/t/topic/opLy 著作权归作者所有。请勿转载和采集!