使用列值命名excel文件+;python中这些值的别名

使用列值命名excel文件+;python中这些值的别名,python,excel,pandas,dataframe,naming,Python,Excel,Pandas,Dataframe,Naming,DF看起来像这样,扩展了数千行(即可能的“Type”和“Name”的每个组合) 我已按“类型”和“名称”对数据帧进行分组 | total | big | med | small| Type | Name | |:-----:|:-----:|:-----:|:----:|:--------:|:--------:| | 5 | 4 | 0 | 1 | Pig | John | | 6 | 0 | 3

DF看起来像这样,扩展了数千行(即可能的“Type”和“Name”的每个组合)

我已按“类型”和“名称”对数据帧进行分组

| total |  big  |  med  | small|   Type   |   Name   |
|:-----:|:-----:|:-----:|:----:|:--------:|:--------:| 
|   5   |   4   |   0   |   1  |   Pig    |   John   |
|   6   |   0   |   3   |   3  |   Pig    |   John   | 
|   5   |   2   |   3   |   0  |   Pig    |   John   |
|   5   |   2   |   3   |   0  |   Pig    |   John   |
然后分别在每个分组的数据帧上运行函数

for idx, df in data.groupby(['Type', 'Name']):
     function_1(df)
     function_2(df)

    with pd.ExcelWriter(f"{'_'.join(idx)}.xlsx") as writer:
        table_1.to_excel(writer, sheet_name='Table 1', index=False)
        table_2.to_excel(writer, sheet_name='Table 2', index=False)
生成的文件名如下所示:

"Pig_John.xlsx"
我想添加别名来分别替换每个“Type”和“Name”,如下所示

Aliases: 

Pig = Type1
Horse = Type2
Cow = Type3
John = Name1
Mike = Name2
Rick = Name3

Example Result:

Pig_John.xlsx = Type1_Name1.xlsx
Horse_Rick.xlsx = Type2_Name3.xlsx

您可以创建一个字典,然后调用字典的键和值,使用
idx=(dct[idx[0]],dct[idx[1]])的每个循环创建一个新的
idx

Aliases: 

Pig = Type1
Horse = Type2
Cow = Type3
John = Name1
Mike = Name2
Rick = Name3

Example Result:

Pig_John.xlsx = Type1_Name1.xlsx
Horse_Rick.xlsx = Type2_Name3.xlsx
dct = {'Pig' : 'Type1',
'Horse' : 'Type2',
'Cow' : 'Type3',
'John' : 'Name1',
'Mike' : 'Name2',
'Rick' : 'Name3'}

df=d.copy()
for idx, d in df.groupby(['Type', 'Name']):
    idx = (dct[idx[0]], dct[idx[1]])
    print(f"{'_'.join(idx)}.xlsx")

Out[1]:
Type3_Name1.xlsx
Type3_Name3.xlsx
Type2_Name2.xlsx
Type2_Name3.xlsx
Type1_Name1.xlsx
Type1_Name2.xlsx