【发布时间】:2015-10-06 17:53:39
【问题描述】:
首先我想说我无论如何都不是专家。我很精通,但是像我年轻的时候一样承担着日程安排和学习 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
【问题讨论】:
标签: python python-2.7 pandas openpyxl