gpt4 book ai didi

python - 使用列值对excel文件进​​行排序python

转载 作者:行者123 更新时间:2023-11-30 21:53:55 25 4
gpt4 key购买 nike

我有 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 文件

最佳答案

这是一种组合文件夹中的所有文件和每个文件中的所有工作表的方法,然后按 DEPTNAME 进行分组,并按文件名 + 对文件夹中的文件进行排序(注意:如果 相同) DEPTNAME 位于 2 个不同的 Excel 文件中,它们在同一文件夹中保存为 2 个不同的文件<- 根据要求):

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

关于python - 使用列值对excel文件进​​行排序python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59489774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com