簡體   English   中英

將多個工作簿中的特定工作表連接到一個 df 時出錯

[英]Error concatenating specific sheet from multiple workbooks into one df

我試圖從大約 300 個 excel 工作簿中分離出一個特定的工作表,並將它們組合成一個 dataframe。

我試過這段代碼:

import pandas as pd
import glob
import openpyxl
from openpyxl import load_workbook

pd.set_option("display.max_rows", 100, "display.max_columns", 100)
allexcelfiles = glob.glob(r"C:\Users\LELI Laptop 5\Desktop\DTP1\*.xlsx")
cefdf = []

for ExcelFile in allexcelfiles:
    wb = load_workbook(ExcelFile)
    for sheet in wb:
        list_of_sheetnames = [sheet for sheet in wb.sheetnames if "SAR" in sheet]
        df = pd.read_excel(ExcelFile, sheet_name = list_of_sheetnames, nrows = 24)
        cefdf.append(df)
df = pd.concat(cefdf)

我從中得到這個錯誤:

TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid

然后我嘗試了這個:

df = pd.DataFrame(pd.read_excel(ExcelFile, sheet_name = list_of_sheetnames, nrows = 24))

我從中得到這個錯誤:

ValueError: If using all scalar values, you must pass an index

您可以連接 DataFrames 的字典,原因是因為list_of_sheetnames中有多個工作表名稱:

for ExcelFile in allexcelfiles:
    wb = load_workbook(ExcelFile)

    list_of_sheetnames = [sheet for sheet in wb.sheetnames if "SAR" in sheet]
    
    dfs = pd.read_excel(ExcelFile, sheet_name = list_of_sheetnames, nrows = 24)
    cefdf.append(pd.concat(dfs))
    
df = pd.concat(cefdf)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM