当前位置: 代码网 > it编程>前端脚本>Python > Pandas+openpyxl进行Excel处理详解

Pandas+openpyxl进行Excel处理详解

2025年02月13日 Python 我要评论
1. 读取多个 excel 文件并合并假设你有一个文件夹,里面包含多个 excel 文件,你想将这些文件合并成一个 dataframe。import pandas as pdimport os# 文件

1. 读取多个 excel 文件并合并

假设你有一个文件夹,里面包含多个 excel 文件,你想将这些文件合并成一个 dataframe。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 创建一个空的 dataframe 来存储所有数据
all_data = pd.dataframe()
# 逐个读取每个 excel 文件并将数据追加到 all_data 中
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path)
    all_data = pd.concat([all_data, df], ignore_index=true)
# 查看合并后的数据
print(all_data.head())

2. 批量处理多个 excel 文件

假设你需要对多个 excel 文件进行相同的处理(例如,添加一列、过滤数据等)。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=true)
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 处理每个 excel 文件
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path)
    # 添加一列
    df['new_column'] = 'some value'
    # 过滤数据
    filtered_df = df[df['some_column'] > 100]
    # 保存处理后的数据
    output_file_path = os.path.join(output_folder, file)
    filtered_df.to_excel(output_file_path, index=false)
print("processing complete.")

3. 从多个 excel 文件中提取特定信息

假设你需要从多个 excel 文件中提取特定的信息(例如,某个特定单元格的数据)。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 存储结果
results = []
# 从每个 excel 文件中提取特定信息
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path)
    # 假设我们需要提取第一行第一列的数据
    specific_value = df.iloc[0, 0]
    # 将结果存储在一个列表中
    results.append((file, specific_value))
# 打印结果
for file, value in results:
    print(f"file: {file}, specific value: {value}")

4. 使用 openpyxl 处理多个 excel 文件

如果你需要更细粒度地控制 excel 文件(例如,修改特定单元格、格式化等),可以使用 openpyxl 库。

import openpyxl
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=true)
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 处理每个 excel 文件
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    workbook = openpyxl.load_workbook(file_path)
    sheet = workbook.active
    # 修改特定单元格
    sheet['a1'] = 'new value'
    # 保存处理后的文件
    output_file_path = os.path.join(output_folder, file)
    workbook.save(output_file_path)
print("processing complete.")

5. 合并多个 excel 文件到一个工作簿的不同工作表

假设你有多个 excel 文件,并希望将它们合并到一个新的 excel 工作簿中的不同工作表中。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
output_file = 'merged_workbook.xlsx'
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 创建一个新的 excelwriter 对象
with pd.excelwriter(output_file, engine='openpyxl') as writer:
    # 处理每个 excel 文件并将数据写入不同的工作表
    for file in excel_files:
        file_path = os.path.join(folder_path, file)
        df = pd.read_excel(file_path)
        # 使用文件名作为工作表名称
        sheet_name = os.path.splitext(file)[0]
        # 写入数据
        df.to_excel(writer, sheet_name=sheet_name, index=false)
print("merging complete.")

6. 批量处理多个 excel 文件并进行数据清洗

假设你需要对多个 excel 文件进行数据清洗,例如删除空行、填充缺失值等。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=true)
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 处理每个 excel 文件
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path)
    # 删除空行
    df.dropna(how='all', inplace=true)
    # 填充缺失值
    df.fillna(0, inplace=true)
    # 保存处理后的数据
    output_file_path = os.path.join(output_folder, file)
    df.to_excel(output_file_path, index=false)
print("data cleaning complete.")

7. 从多个 excel 文件中提取特定列并合并

假设你需要从多个 excel 文件中提取特定列,并将这些列合并成一个新的 dataframe。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 创建一个空的 dataframe 来存储所有数据
all_data = pd.dataframe()
# 逐个读取每个 excel 文件并提取特定列
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path, usecols=['column1', 'column2'])
    # 将提取的数据追加到 all_data 中
    all_data = pd.concat([all_data, df], ignore_index=true)
# 查看合并后的数据
print(all_data.head())

8. 批量重命名多个 excel 文件中的工作表

假设你需要批量重命名多个 excel 文件中的工作表名称。

import openpyxl
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=true)
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 处理每个 excel 文件
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    workbook = openpyxl.load_workbook(file_path)
    # 重命名工作表
    if 'oldsheetname' in workbook.sheetnames:
        sheet = workbook['oldsheetname']
        sheet.title = 'newsheetname'
    # 保存处理后的文件
    output_file_path = os.path.join(output_folder, file)
    workbook.save(output_file_path)
print("sheet renaming complete.")

9. 批量导出 excel 数据到 csv 文件

假设你需要将多个 excel 文件中的数据批量导出为 csv 文件。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/csvs'
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=true)
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 处理每个 excel 文件
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path)
    # 生成输出文件路径
    base_name = os.path.splitext(file)[0]
    output_file_path = os.path.join(output_folder, f'{base_name}.csv')
    # 导出为 csv 文件
    df.to_csv(output_file_path, index=false)
print("export to csv complete.")

10. 批量处理多个 excel 文件并进行数据分析

假设你需要对多个 excel 文件进行数据分析,例如计算总和、平均值等。

import pandas as pd
import os
# 文件夹路径
folder_path = 'path/to/your/excel/files'
# 获取文件夹中的所有 excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 创建一个空的 dataframe 来存储所有数据
all_data = pd.dataframe()
# 逐个读取每个 excel 文件并将数据追加到 all_data 中
for file in excel_files:
    file_path = os.path.join(folder_path, file)
    df = pd.read_excel(file_path)
    # 将数据追加到 all_data 中
    all_data = pd.concat([all_data, df], ignore_index=true)
# 进行数据分析
total_sum = all_data['some_column'].sum()
average_value = all_data['some_column'].mean()
# 打印结果
print(f"total sum: {total_sum}")
print(f"average value: {average_value}")

到此这篇关于pandas+openpyxl进行excel处理详解的文章就介绍到这了,更多相关pandas openpyxl处理excel内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com