python中导入多个excel文件,操作,然后导出同一目录下的多个文件

问题描述

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

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

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

如有任何建议,我们将不胜感激。

谢谢!

解决方法

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

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

enter image description here

我对每行的作用添加了一个简短的描述。如果有什么不清楚的地方,请告诉我。

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)

我知道这可能不是最有效的方式,但它可能会满足您的需求。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...