如何通过 sheet 名称解析 excel sheets (Pandas)
How to parse excel sheets by sheet name (Pandas)
我目前有一个代码可以遍历目录中的所有 excel 文件,并将工作簿中的 sheet # 中的所有数据解析为最后一个 sheet。我试图让代码通过特定的 sheet 名称访问 sheets,所有 excel 文件都有一个 sheet 标题 "Data Narrative" 我正在尝试使用权。我如何让它工作而不是通过索引位置获取 sheets?
当前代码如下。
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)
我会为此使用 pd.read_excel()
,因为它有一个要指定给 sheet 名称的参数。假设您所有的文件名都在一个名为 f_names
:
的列表中
combined = pd.concat(
pd.read_csv(open(f, 'rb'), sheet_name="Data Narrative") for f in f_names
)
欢迎来到 Whosebug,kaner32!
您可以只使用 sheet_name='Data Narrative
作为 .parse
或 pd.ExcelFile
class 调用函数中的参数。
有关更多信息,请查看文档 here。
我在 this post 中找到了解决方案。
我目前有一个代码可以遍历目录中的所有 excel 文件,并将工作簿中的 sheet # 中的所有数据解析为最后一个 sheet。我试图让代码通过特定的 sheet 名称访问 sheets,所有 excel 文件都有一个 sheet 标题 "Data Narrative" 我正在尝试使用权。我如何让它工作而不是通过索引位置获取 sheets?
当前代码如下。
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)
我会为此使用 pd.read_excel()
,因为它有一个要指定给 sheet 名称的参数。假设您所有的文件名都在一个名为 f_names
:
combined = pd.concat(
pd.read_csv(open(f, 'rb'), sheet_name="Data Narrative") for f in f_names
)
欢迎来到 Whosebug,kaner32!
您可以只使用 sheet_name='Data Narrative
作为 .parse
或 pd.ExcelFile
class 调用函数中的参数。
有关更多信息,请查看文档 here。
我在 this post 中找到了解决方案。