【问题标题】:Import multiple excel files in python, manipulate, and then export multiple files in same directory [closed]在python中导入多个excel文件,操作,然后在同一目录中导出多个文件[关闭]
【发布时间】:2021-05-02 04:13:12
【问题描述】:

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

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

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

任何建议将不胜感激。

谢谢!

【问题讨论】:

  • 你试过什么?你有什么错误?我认为第一步是使用ospathlib 模块解析所有你可以做到的文件

标签: python excel pandas merge


【解决方案1】:

我创建了一个试用文件夹,我认为它与您的相似。我只为 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)

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

【讨论】:

  • 感谢您的解决方案,根据您的逻辑,我能够解决任务。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
相关资源
最近更新 更多