【问题标题】:How to parse excel sheets by sheet name (Pandas)如何按工作表名称解析 excel 工作表(熊猫)
【发布时间】:2019-11-27 21:01:49
【问题描述】:

我目前有一个代码运行目录中的所有 excel 文件,并将工作簿中工作表 # 中的所有数据解析为最终工作表。我试图让代码通过特定的工作表名称访问工作表,所有 excel 文件都有一个标题为“数据叙述”的工作表,我正在尝试访问。如何让它工作而不是按索引位置抓取工作表?

当前代码如下。

import pandas as pd
from os import listdir
from os.path import isfile, join

onlyfiles = [f for f in listdir('ALL EDTs') if isfile(join('ALL EDTs', f))]



# filenames
excel_names = onlyfiles

# read them in
excels = [pd.ExcelFile('ALL EDTS/'+ name) for name in excel_names]

# turn them into dataframes
frames = [x.parse(x.sheet_names[3], header=None,index_col=None) for x in 
excels]

# delete the first row for all frames except the first
# i.e. remove the header row -- assumes it's the first
frames[1:] = [df[4:] for df in frames[1:]]

# concatenate them..
combined = pd.concat(frames)

# write it out
combined.to_excel("all.xlsx", header=False, index=False)

【问题讨论】:

    标签: python excel pandas parsing concat


    【解决方案1】:

    欢迎来到 Stackoverflow,kaner32!

    您可以只使用sheet_name='Data Narrative 作为.parsepd.ExcelFile 类调用函数中的参数。

    更多信息请查看文档here

    我在this 帖子中找到了解决方案。

    【讨论】:

      【解决方案2】:

      我会为此使用pd.read_excel(),因为它有一个参数来指定工作表名称。假设你所有的文件名都在一个名为f_names的列表中:

      combined = pd.concat(
                    pd.read_csv(open(f, 'rb'), sheet_name="Data Narrative") for f in f_names
                 )
      

      【讨论】:

        猜你喜欢
        • 2018-10-05
        • 2010-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-12
        • 1970-01-01
        • 2020-02-12
        • 2010-12-02
        相关资源
        最近更新 更多