使用列值python对excel文件排序

2024-05-19 00:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有n个excel文件,需要根据列的值对它们进行排序。事实上,在创建子文件夹时,我需要组织放置在特定文件夹下的excel文件,并且每个子文件夹包含具有相同DEPTNAME的excel文件,要知道DEPTNAME是一个列名,每个excel文件有m个工作表,但所有工作表都具有相同的DEPTNAME。你知道吗

示例: 包含4个excel文件的文件夹:

df1= pd.DataFrame({'Last Name':[‘Stark’, ‘Stark’, ‘ Stark’, ‘Stark’],
 'FirstName':['Arya', ,'Arya','Arya','Arya',],
 'DEPTNAME':['Sécu','Sécu','Sécu','Sécu']})

enter image description here

df2= pd.DataFrame({'Last Name':[‘Lannister’, ‘Lannister’, ‘ Lannister’, ‘Lannister’],
 'FirstName':['Cersei', ,'Cersei','Cersei','Cersei',],
 'DEPTNAME':['Auto','Auto','Auto','Auto']})

enter image description here

df3= pd.DataFrame({'Last Name':[‘Snow’, ‘Snow’, ‘ Snow’, ‘Snow’, ‘ Snow’, ‘Snow’],
         'FirstName':['Jon', 'Jon','Jon','Jon','Jon','Jon'],
         'DEPTNAME':['Aero','Aero','Aero','Aero','Aero','Aero']})

enter image description here

df4= pd.DataFrame({'Last Name':[‘Lannister’, ‘Lannister’, ‘ Lannister’, ‘Lannister’],
         'FirstName':['Tyrion', 'Tyrion','Tyrion','Tyrion',],
         'DEPTNAME':['Aero','Aero','Aero','Aero']})

enter image description here

现在我需要自动创建3个文件夹:SécuAeroAuto。你知道吗

Sécu将包含一个excel文件

Aero将包含两个excel文件

Auto将包含一个excel文件

知道我的初始文件夹包含n个包含多张工作表的excel文件是否可行?你知道吗


Tags: 文件name文件夹dataframeautoexcelpdlast
1条回答
网友
1楼 · 发布于 2024-05-19 00:20:51

这里有一种方法,它将文件夹中的所有文件和每个文件中的所有工作表组合在一起,然后在DEPTNAME上分组,文件名+对文件夹中的文件进行排序(注意:如果相同的DEPTNAME在两个不同的excel文件中,它们将另存为同一文件夹中的两个不同文件<;-根据请求):

def myf(folder,files_to_be_created_in_folder):
    """ folder is the path to input files and files_to_be_created_in_folder
         is the path where the directories are to be created"""
    folder = folder
    list_of_files=os.listdir(folder)
    combined_sheets={i[:-5]:pd.concat(pd.read_excel(os.path.join(folder,i),sheet_name=None)
        .values(),sort=False)for i in list_of_files}
    combined_all_files=pd.concat(combined_sheets.values(),keys=combined_sheets.keys())
    d={i:g for i,g in combined_all_files.groupby(['DEPTNAME'
             ,combined_all_files.index.get_level_values(0)])}
    to_create_folder=files_to_be_created_in_folder
    for k,v in d.items():
        newpath=os.path.join(to_create_folder,k[0])
        if not os.path.exists(newpath):
            os.makedirs(newpath)
        v.to_excel(os.path.join(newpath,f"{k[1]}.xlsx"),index=False)

myf(r'C:\path_to_files\test_folder',r'C:\path_to_write\New folder') #replace paths carefully

为了进行测试,我尝试了打印基于this解决方案的文件夹树,该解决方案描述了一个文件夹树:

ptree(r'C:\path_to_files\test_folder')

test_folder/
|  test_1.xlsx
|  test_2.xlsx
|  test_3.xlsx
|  test_4.xlsx

ptree(r'C:\path_to_write\New folder') #this also has the test folder

New folder/
|  Aero/
|   |  test_3.xlsx
|   |  test_4.xlsx
|  Auto/
|   |  test_2.xlsx
|  Sécu/
|   |  test_1.xlsx
|  test_folder/
|   |  test_1.xlsx
|   |  test_2.xlsx
|   |  test_3.xlsx
|   |  test_4.xlsx

相关问题 更多 >

    热门问题