首页 > 解决方案 > 在python中导入多个excel文件,操作,然后在同一个目录下导出多个文件

问题描述

我在同一个文件夹中放置了 50 个不同的 excel 文件中的 50 个人的一些数据。对于每个人,数据都存在于五个不同的文件中,如下所示:

示例: Person1_a.xls、Person1_b.xls、Person1_c.xls、Person1_d.xls、Person1_e.xls。

每个 Excel 工作表都有两列和多个工作表。我需要创建一个文件 Person1.xls,它将所有这些文件的第二列组合在一起。相同的过程应该适用于所有 50 人。

任何建议,将不胜感激。

谢谢!

标签: pythonexcelpandasmerge

解决方案


我创建了一个试用文件夹,我认为它与您的相似。我只为 Person1 和 Person3 添加了数据。

在附图中,名为Person1Person3的文件是导出的文件,其中仅包含每个人的第二列。所以现在每个人都有自己的档案。

在此处输入图像描述

我在每一行的作用上添加了一个小描述。如果有不清楚的地方,请告诉我。

import pandas as pd
import glob

path = r'C:\..\trial' # use your path where the files are
all_files = glob.glob(path + "/*.xlsx") # will get you all files with an extension .xlsx in a folder

li = []
for i in range(0,51): # numbers from 1 to 50 (for the 50 different people)
    for f in all_files:
        if str(i) in f: # checks if the number (i) is in the excel name
            df = pd.read_excel(f,
                                 sheet_name=0, # import 1st sheet
                                 usecols=([1])) # only import column 2
            df['person'] = f.rsplit('\\',1)[1].split('_')[0] # get the name of the person in a column
            li.append(df) # add it to the list of dataframes

all_person = pd.concat(li, axis=0, ignore_index=True)  # concat all dataframes imported      

然后就可以导出到同一个路径,每个不同的人不同的excel文件

for i,j in all_person.groupby('person'):
    j.to_excel(f'{path}\{i}.xlsx', index = False)

我知道这可能不是最有效的方法,但它可能会为您提供所需的东西。


推荐阅读