python - 在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 添加了数据。
在附图中,名为Person1和Person3的文件是导出的文件,其中仅包含每个人的第二列。所以现在每个人都有自己的档案。
我在每一行的作用上添加了一个小描述。如果有不清楚的地方,请告诉我。
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)
我知道这可能不是最有效的方法,但它可能会为您提供所需的东西。
推荐阅读
- xslt - XSLT 替换命名空间并添加新的(未使用的)命名空间
- python-3.x - 尝试导入 pyPDF2 时找不到模块
- azure - Azure 阻止租户删除需要删除不存在的域服务
- firebase - firebase 通知在后台颤振中不起作用
- python - 指定重新采样时的开始时间
- ios - 如何修复来自 react-native-video 上的 s3 aws 的 IOS 渲染流视频上的“AVFoundationErrorDomain - 代码 -11800”?
- python - 如何在 vs studio 代码中导入自己的对象?
- javascript - 试图做到这一点,所以我的命令只适用于一个公会 Discord.js
- android - 将游标信息打印到 logcat
- c++ - 求平均 GPA C++