如何用Pandas实现类VBA的动态筛选表格并导出新文件
问题描述
我有一份CSV格式的表格数据,结构如下:
| ID | employee | date | value1 | value2 |
|---|---|---|---|---|
| 1 | a | 2022-01-01 | 123 | 456 |
| 2 | b | 2022-01-01 | 123 | 456 |
| 3 | a | 2022-01-01 | 123 | 456 |
| 4 | c | 2022-01-01 | 123 | 456 |
| 5 | d | 2022-01-01 | 123 | 456 |
| 6 | b | 2022-01-01 | 123 | 456 |
| 7 | e | 2022-01-01 | 123 | 456 |
| 8 | e | 2022-01-01 | 123 | 456 |
此前我在Excel中用VBA编写宏,实现按employee列筛选表格并为每个员工生成独立工作簿:先提取employee列唯一值存入字典,再遍历字典键值筛选数据,最终为每个员工(如a、b、c、d、e)生成仅包含其对应数据的工作簿,例如员工a的结果如下:
| ID | employee | date | value1 | value2 |
|---|---|---|---|---|
| 1 | a | 2022-01-01 | 123 | 456 |
| 3 | a | 2022-01-01 | 123 | 456 |
对应的VBA代码(已修正原代码中的列索引错误):
Sub Filter_Copy() Dim rng As Range Dim wb_new As Workbook Dim dic As Object Dim cell As Range Dim key As Variant Set rng = Table1.ListObjects("table").Range Set dic = CreateObject("Scripting.Dictionary") For Each cell In Range("table[employee]") dic(cell.Value) = 0 Next cell For Each key In dic.keys rng.AutoFilter 2, key ' employee是第2列,原代码的5为错误值 Set wb_new = Workbooks.Add rng.SpecialCells(xlCellTypeVisible).Copy wb_new.Worksheets(1).Range("A1") wb_new.Close True, ThisWorkbook.Path & "\" & key & ".xlsx" Next key End Sub
现在我想用Python的Pandas实现完全相同的功能,已能手动通过df.employee == "a"筛选并导出,但不知道如何动态遍历employee列的唯一值批量处理。目前完成的代码片段:
import pandas as pd file = "filename.csv" df = pd.read_csv(file) dict = dict(df["employee"].unique())
Pandas解决方案
不需要用字典存储唯一值,直接遍历唯一值或使用groupby即可实现批量处理,以下是两种可行方法:
方法1:遍历员工唯一值
import pandas as pd import os file = "filename.csv" df = pd.read_csv(file) # 获取employee列的所有唯一值 unique_employees = df["employee"].unique() # 获取当前脚本所在路径,对应VBA中的ThisWorkbook.Path save_dir = os.path.dirname(os.path.abspath(__file__)) for emp in unique_employees: # 筛选当前员工的数据 emp_data = df[df["employee"] == emp] # 导出为Excel文件,文件名以员工名命名 emp_data.to_excel(os.path.join(save_dir, f"{emp}.xlsx"), index=False)
方法2:使用groupby更高效
import pandas as pd import os file = "filename.csv" df = pd.read_csv(file) save_dir = os.path.dirname(os.path.abspath(__file__)) # 按employee分组,遍历每个分组导出 for emp, group in df.groupby("employee"): group.to_excel(os.path.join(save_dir, f"{emp}.xlsx"), index=False)
关键说明
index=False:避免将Pandas的索引列写入Excel,和VBA导出的格式保持一致os.path.join:自动适配不同系统的路径分隔符,避免路径拼接错误- 两种方法均能实现与VBA完全一致的效果:为每个员工生成独立的Excel文件,仅包含该员工的所有对应数据
内容的提问来源于stack exchange,提问作者Denis Böck
相关产品推荐
相关产品推荐

