使用pandas对Excel文件进行分组并拆分成多个子Excel

遇到一个需求:Excel表格为某行业的销量数据,需要对品牌进行分组,然后把不同品牌的数据放到不同的Excel表格中。

import pandas as pd

df = pd.read_excel("result.xlsx")
#对品牌列去重,生成list
index_list = df.品牌.unique() 
#计算品牌个数
lenth_index = len(index_list) 
for n in range(lenth_index):
    #读取该品牌的所有数据
    data1=df[df['品牌'] == index_list[n]]  
    #sheet命名
    sheet_name1=index_list[n]  
    #保存路径命名,为相对路径
    path_to_file='./result/' + sheet_name1+".xlsx"  
     #保存,无索引
    data1.to_excel(path_to_file, sheet_name=sheet_name1,index=False)
    print(path_to_file+"已生成")
print("任务已生成,累计生成%d个Excel文件"%lenth_index)

猜你喜欢

转载自blog.csdn.net/ramblerviper/article/details/119717735