Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

python - List of sheet_names then read under a condition

What I'm trying to do, I think I'm close to, is to read an excel file, create a list of all sheet_names found in the file, and then if the name contains "Activity" then read it and then concatenate it in a data frame. I would appreciate your expertise on this matter.

df_ac = pd.DataFrame()

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

for sheet in sheets:
    df = pd.read_excel(r"C:UsersosunaOneDriveDesktop" + '\' + ffile, sheet_name=sheet, read_only=True)
    df_ac = pd.concat([df, df_ac], ignore_index=True)
question from:https://stackoverflow.com/questions/65912805/list-of-sheet-names-then-read-under-a-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use append as well instead of 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...