然后在条件下读取的图纸名称列表

2024-09-30 12:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想我要做的是读取一个excel文件,创建一个文件中所有工作表名称的列表,如果名称包含“活动”,则读取它,然后将其连接到数据框中。我将感谢你在这件事上的专业知识

df_ac = pd.DataFrame()

wb = load_workbook(r"C:\Users\bosuna\OneDrive\Desktop" + '\\' + ffile, read_only=True)
sheets = [s for s in wb if "Activity" in wb]

for sheet in sheets:
    df = pd.read_excel(r"C:\Users\bosuna\OneDrive\Desktop" + '\\' + ffile, sheet_name=sheet, read_only=True)
    df_ac = pd.concat([df, df_ac], ignore_index=True)

Tags: 文件in名称truedfreadonedriveexcel
3条回答

您也可以使用append代替concat

import pandas as pd

x1 = pd.ExcelFile('name of file.xlsx')
empty_df = pd.DataFrame()


for sheet in x1.sheet_names:  # iterate through sheet name
    if 'ACTIVITY' in sheet:  # check wether activity is present in sheet name
       df = pd.read_excel('name of file.xlsx',sheet_name = sheet)
       empty_df = empty_df.append(df)

我不完全确定我是否理解,但我假设您正在尝试将“活动”表加载到panda数据框中(如果它存在于工作簿中)。如果是这样,我建议以下解决方案:

wb = load_workbook(r"C:\Users\bosuna\OneDrive\Desktop" + '\\' + ffile, read_only=True)
if 'Activity' in wb.sheetnames:
    df = pd.DataFrame(wb['Activity' ].values)

在列表理解(第4行)中,您正在检查wb中的"Activity",而不是s(图纸名称)

如果其中一张为“活动”,则这相当于仅迭代所有工作表

据我所知,预期行为仅在工作表名称本身包含短语“活动”时阅读工作表,而这与实际行为不同

用这个替换第4行

sheets = [s for s in wb if "Activity" in s]

相关问题 更多 >

    热门问题