首先,我想说我绝不是专家.我很精通,但是却像我年轻时那样,要承担日程安排和学习Python的重担!
题:
我有一本工作簿,有时会有多个工作表.在工作簿中阅读时,我将不知道工作表的张数或工作表名称.每张纸上的数据排列都相同,有些列的名称为“未命名”.问题是,我尝试或在网上找到的所有内容都使用pandas.ExcelFile来收集所有工作表,但这很好,但我需要能够跳过4行,然后仅读取42行并解析特定的列.尽管工作表可能具有完全相同的结构,但列名可能相同或不同,但希望将它们合并.
所以这是我所拥有的:
import pandas as pd
from openpyxl import load_workbook
# Load in the file location and name
cause_effect_file = r'C:\Users\Owner\Desktop\C&E Template.xlsx'
# Set up the ability to write dataframe to the same workbook
book = load_workbook(cause_effect_file)
writer = pd.ExcelWriter(cause_effect_file)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
# Get the file skip rows and parse columns needed
xl_file = pd.read_excel(cause_effect_file, skiprows=4, parse_cols = 'B:AJ', na_values=['NA'], convert_float=False)
# Loop through the sheets loading data in the dataframe
dfi = {sheet_name: xl_file.parse(sheet_name)
for sheet_name in xl_file.sheet_names}
# Remove columns labeled as un-named
for col in dfi:
if r'Unnamed' in col:
del dfi[col]
# Write dataframe to sheet so we can see what the data looks like
dfi.to_excel(writer, "PyDF", index=False)
# Save it back to the book
writer.save()
我正在使用的文件的链接如下
Excel File
解决方法:
尝试根据您的特定需求修改以下内容:
import os
import pandas as pd
df = pd.DataFrame()
xls = pd.ExcelFile(path)
然后遍历所有可用的数据表:
for x in range(0, len(xls.sheet_names)):
a = xls.parse(x,header = 4, parse_cols = 'B:AJ')
a["Sheet Name"] = [xls.sheet_names[x]] * len(a)
df = df.append(a)
您可以调整标题行和列以读取每张纸.我添加了一个列,该列将指示该行来自的数据表的名称.