首页 > 解决方案 > Python Pandas - 遍历 .xlsx 文件的文件夹,仅使用正则表达式从名称中带有 xx.xx 的 Excel 选项卡添加数据

问题描述

我有近 30 个 Excel 文件的数据集。我已经能够遍历文件夹并将它们全部附加到一个数据集中。我的问题是这些 Excel 文件中的一些具有我需要的多个选项卡的数据。我需要的所有选项卡都具有以选项卡名称表示的相同日期模式(例如,01.21)。显然正则表达式是我需要的,我知道我需要的正则表达式模式,我的问题是我不知道如何使用 Pandas 循环遍历每个 Excel 文件,使用正则表达式检查选项卡名称,并且只添加来自具有 xx 的选项卡的数据.xx 在字符串中。例如,如果我打开一个 Excel 文件并且有 3 个选项卡:“data 01.22”、“financials”和“data 03.23”,我只希望它添加来自“data 01.22”和“data 03.23”的数据。

我需要在这些选项卡中识别名称模式的正则表达式模式是 [0-9][0-9]+.[0-9][0-9]。我知道我很接近,但我错过了一些关键的东西,感谢任何帮助。

import pandas as pd
import os
import re

# filenames
files = os.listdir()    
excel_names = list(filter(lambda f: f.endswith('.xlsx'), files))

# read them in
excels = [pd.ExcelFile(name, engine='openpyxl') for name in excel_names]

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

#These are the tabs 
sh = [x.sheet_names for x in excels]

# I know I need to use this regex below, but where is the question:

#sheet_match = re.findall("[0-9][0-9]+\.[0-9][0-9]", s)

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

# concatenate 
combined = pd.concat(frames)

# export 
combined.to_excel("combinedfiles.xlsx", header=False, index=False)


标签: pythonexcelregexpandasdataframe

解决方案


你真的很接近,你只需要用re.match. 循环遍历每个 Excel 文件,对于每个文件,打开它并获取选项卡名称列表 ( excel_file.sheet_names),使用re.match您已经定义的表达式来获取与所需模式匹配的选项卡。阅读这些表格 ( sheet_name=valid_sheets) 的内容,根据您的特定情况调整标题和索引,然后将每个 Excel 文件的提取内容添加到列表中。连接列表pd.concat并生成新的 excel 文件。

import pandas as pd
import os
import re

# filenames
files = os.listdir()
excel_names = list(filter(lambda f: f.endswith('.xlsx'), files))

regex = r'[0-9][0-9]+\.[0-9][0-9]'

frame_list = []
# loop through each Excel file
for name in excel_names:
    # open one excel file
    excel_file = pd.ExcelFile(name, engine='openpyxl')
    # get the list of tabs that have xx.xx in the string
    valid_sheets = [tab for tab in excel_file.sheet_names if re.match(regex, tab)]
    # read the content from that tab list
    d = excel_file.parse(sheet_name=valid_sheets, header=0)
    # add the content to the frame list
    frame_list += list(d.values())

combined = pd.concat(frame_list)
combined.to_excel("combinedfiles.xlsx", header=False, index=False)

推荐阅读