【问题标题】:Looping through a folder to merge several excel sheets into one column循环浏览文件夹以将多个 Excel 工作表合并为一列
【发布时间】:2016-11-06 06:48:35
【问题描述】:

我有几本工作簿,每本都有三张纸。我想遍历每个工作簿并将 sheet_1 中的所有数据合并到一个新的 workbook_1 文件中,sheet_2 到 workbook_2 文件中,sheet_3 到 workbook_3 中。

据我所知,下面的脚本做了我需要的一切,除了追加数据之外,它会覆盖上一次迭代的数据。

为了简洁起见,我已经缩短、清理和简化了我的脚本,但如果需要,我很乐意分享完整的脚本。

import pandas as pd
import glob

search_dir= ('/Users/PATH/*.xlsx')

sheet_names = ['sheet_1','sheet_2','sheet_2']

def a_joiner(sheet):
    for loop_x in glob.glob(search_dir):   
    try:

        if sheet == 'sheet_1':
            id_file= pd.ExcelFile(loop_x)                            
            df_1 = id_file.parse(sheet, header= None)             
            writer= pd.ExcelWriter('/Users/PATH/%s.xlsx' %(sheet), engine= 'xlsxwriter')                         
            df_1.to_excel(writer)                    
            writer.save()

        elif sheet == 'sheet_2':
           #do same as above

        else:
           #and do same as above again

    except Exception as e:
       print('Error:',e)

for sheet in sheet_names:
    a_joiner(sheet)

【问题讨论】:

    标签: python excel pandas merge glob


    【解决方案1】:

    您还可以轻松附加数据,例如:

    df = []
    for f in ['c:\\file1.xls', 'c:\\ file2.xls']:
        data = pd.read_excel(f, 'Sheet1').iloc[:-2]
        data.index = [os.path.basename(f)] * len(data)
        df.append(data)
    
    df = pd.concat(df)
    

    来自: Using pandas Combining/merging 2 different Excel files/sheets

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2018-06-04
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多