[英]How can I improve the runtime of reading multiple excel files using python?
我创建了 function 迭代包含 excel 文件的文件夹并创建所有工作表中所有标题的列表。 它工作正常,但非常慢。 您对如何改进它有任何想法吗? 谢谢!
import glob
# file directory
path = r'C:\Users\John\Excel_folder'
all_files = glob.glob(path + "/*.xlsx")
def get_columns(file):
sheets = pd.ExcelFile(file).sheet_names
for sheet in sheets:
for i in (list(pd.read_excel(file, sheet, nrows=0).columns)):
col.append(i)
col=[]
for i in all_files:
get_columns(i)
col
您可以将None
传递给sheet_name
中的read_excel
以一次读取所有工作表。 它创建了一个 dataframe 的字典,所以最后你可以使用列表理解。
def get_columns(file):
return [c
for df in pd.read_excel(file,
sheet_name=None,
nrows=0).values()
for c in df.columns]
col = [c for file in all_files for c in get_columns(file)]
它应该更快,因为您打开文件一次而不是多次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.