【问题标题】:Python - Load multiple excel files with multiple sheets in it with specific columnsPython - 加载多个带有特定列的多个工作表的excel文件
【发布时间】:2021-05-18 10:29:59
【问题描述】:

我有一个需要使用 Python 加载 excel 文件的问题场景

  • 从一个文件夹中加载多个 excel 文件 - 完成
  • 每个 excel 文件都有多个工作表 - 完成
  • 只需要加载所需的列('接收日期'、'处理日期'、'处理编号'、'任务名称'、'系列'、'办公室'、'部门'、'单位经理'、 'AM'),其他列需要忽略/删除,如果某些工作表中不存在上述列,则不应引发错误。
  • 将所有数据加载到单个数据帧中

----- 代码------

import pandas as pd
import os
import glob

def getfilepath():
    path = 'C:/Users/Tracking Logs/'
    files=(os.listdir(path))
    allfiles = glob.glob(path+"*.xlsx")

def getdatafromexcel():
    for file in allfiles:
        rawdf = pd.read_excel(file,sheet_name=None,na_values='null',keep_default_na=False,dtype=object,date_parser=True)
        cols=('Receive Date','Process Date','Process Number','Task Name','Series','Office','Department','Unit Manager','AM/AA/PC')
        display(df)
    
getfilepath()
getdatafromexcel()

【问题讨论】:

  • 您可以将cols 传递给您的pd.read_excel 函数调用,例如pd.read_excel(...,usecols=cols) 注意cols 应该是一个列表而不是一个元组,请参阅here
  • 谢谢@Umar.H,这在我使用元组时有所帮助,现在使用元组后我收到错误消息,说有几列不匹配。在某些情况下,所有工作表都没有这些列,因此我需要忽略加载该特定工作表。
  • 我相信你可以弄清楚 :) 你可以使用毯子 try except 与列不匹配时显示的错误。
  • 是的@Umar.H,让我从这里开始。
  • 感谢@Umar.H,我已经发布了。

标签: python-3.x pandas xlrd


【解决方案1】:

我找到了解决办法:

import pandas as pd
import os
import glob
from IPython.display import HTML,display
from openpyxl import load_workbook    

path = 'C:/Users/Tracking Logs/'
cols = ['Receive Date','Process Date','Task Name','Series','Office','Department','Unit Manager','AM/AA/PC']

def getfilepath(path):    
    files=(os.listdir(path))
    allfiles = glob.glob(path+"*.xlsx") 
    #print('Allfiles: ',allfiles)
    return allfiles

def getdatafromexcel(cols,allfiles):   
    for i in range(len(allfiles)): 
        print('\nCounter: ',i,' \nFilenames: ',allfiles[i])         
        wb = load_workbook(allfiles[i],read_only=True)                     
        for sheetname in wb.sheetnames:    
            print('Sheetname: ',sheetname)
            try:                
                df = pd.read_excel(allfiles[i],sheet_name=sheetname,na_values='null',usecols=cols,
                           keep_default_na=False,dtype=object)
                Indexnames = df[(df["Task Name"] == '') & (df["Series"] == '') & (df["Office"] == '')].index
                df.drop(Indexnames,inplace=True)
                display(df)
                fulldf=fulldf.append(df,ignore_index=True)             
            except Exception as e:
                print(e)                                          
            finally:   
                print('this executed')
                wb.close()                       
    display(fulldf)
    
allfiles = getfilepath(path)
getdatafromexcel(cols,allfiles)

【讨论】:

  • 别忘了接受你自己的答案;)
【解决方案2】:

可以使用 pd.ExcelFile 和 pd.read_excel 来获得所需的结果。

def getdatafromexcel():
    for file in allfiles:
        xl = pd.ExcelFile(file)
        res = len(xl.sheet_names)

    
    if res>1:
        for i in range(1, res+1):
            df = pd.read_excel(file, sheet_name= '%d' %i)
            # Do selection, preprocessing what you want here

            if i == 1:
                df.to_csv(<your_path> + '1.csv')
                df_1 = pd.read_csv(<your_path> +  '1.csv')

            if i > 1:
                df_1 = pd.concat([df_1, df])

    else: 
        df_1 = pd.read_excel(file)
        # Do selection, preprocessing what you what here
        df_1.to_csv(<your_path> + '.csv', index= False)

【讨论】:

  • 感谢@Pawan Jain 的投入和时间,我尝试了几件事,现在已修复。
猜你喜欢
  • 2017-04-28
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2018-07-03
  • 1970-01-01
  • 2020-03-05
相关资源
最近更新 更多