Python 根据筛选条件编写具有动态工作表名称的excel文件

Python 根据筛选条件编写具有动态工作表名称的excel文件,python,pandas,dataframe,data-manipulation,Python,Pandas,Dataframe,Data Manipulation,我有个小问题 我正在尝试将完成的excel文件写入Pandas数据框,并根据筛选条件创建不同的工作表名称: #I created a variable to give me the unique names in the column I want to filter Different_Versicherer = commissions_df.Versicherer.unique() # I create an empty list to hold the frames Versichere

我有个小问题

我正在尝试将完成的excel文件写入Pandas数据框,并根据筛选条件创建不同的工作表名称:

#I created a variable to give me the unique names in the column I want to filter
Different_Versicherer = commissions_df.Versicherer.unique()

# I create an empty list to hold the frames
Versicherer = []*len(Different_Versicherer)

# I tried iterate through the unique column and do the filtering. 
for i in range(len(Different_Versicherer)):
    Versicherer[i] = commissions_df[commissions_df.Versicherer == Different_Versicherer[i]]
过滤的想法是可行的,但不可行的是,我希望动态地更改工作表并将其添加到excel文件中


请您提供建议?

如果没有示例数据,很难给出答案,但我认为您需要这样的答案:

import pandas as pd
df = pd.DataFrame({'var':['a','a','b','c','c','c'], 'value':[1, 2, 3, 4, 5, 6]})

writer = pd.ExcelWriter('example.xlsx')
for unique_var in df['var'].unique():
    frame = df[df['var'] == unique_var]
    frame.to_excel(writer, sheet_name=unique_var)
writer.save()
这将创建一个excel文件,其中包含3个工作表(“a”、“b”、“c”),并对原始数据框进行过滤,以在每种情况下匹配该值

这也可以使用
分组方式来完成:

for unique_var, frame in df.groupby('var'):
    # repeat code

很好,这看起来还可以,但是我在写的时候,其中一个名字出现了一个错误。无效工作表名称:Excel工作表名称“Allianz Private KrankeInversicherungs AG”必须为空。您需要缩短该工作表的名称。这是excel强加的限制。快速修复方法是将代码更改为
sheet\u name=unique\u var[:31]