如何无需手动指定行列,从多表格Excel读取汇总表至Pandas DataFrame?
读取Excel中汇总表为Pandas DataFrame的非手动指定方法
方法1:通过表头关键词自动定位
如果汇总表的表头包含特征关键词(比如“汇总”),可以先遍历工作表找到表头位置,再读取数据:
import pandas as pd # 先读取全表数据,不预设表头 temp_data = pd.read_excel('你的文件路径.xlsx', sheet_name='目标工作表名', header=None) # 定位包含“汇总”关键词的表头行(按需修改关键词) header_index = temp_data[temp_data.apply(lambda row: row.str.contains('汇总', na=False).any(), axis=1)].index[0] # 从表头行开始读取数据,并自动识别列名 summary_df = pd.read_excel('你的文件路径.xlsx', sheet_name='目标工作表名', header=header_index) # 清理空行空列 summary_df = summary_df.dropna(how='all').dropna(axis=1, how='all')
方法2:利用openpyxl定位连续数据区域
Excel中的表格通常是连续非空单元格组成,可借助openpyxl遍历工作表,找到符合特征的汇总表区域:
import pandas as pd from openpyxl import load_workbook wb = load_workbook('你的文件路径.xlsx') ws = wb['目标工作表名'] # 查找汇总表起始行(假设表头是前20行中首个多列非空的行) start_row = None for row in ws.iter_rows(min_row=1, max_row=20): non_empty = [cell.value for cell in row if cell.value is not None] if len(non_empty) >= 3: # 按需调整列数阈值 start_row = row[0].row break # 查找汇总表结束行(从起始行向下直到连续空行) end_row = start_row for row in ws.iter_rows(min_row=start_row + 1): if all(cell.value is None for cell in row): break end_row = row[0].row # 查找汇总表的列范围 start_col, end_col = None, None for cell in ws[start_row]: if cell.value is not None and start_col is None: start_col = cell.column if cell.value is not None: end_col = cell.column # 读取目标区域为DataFrame summary_df = pd.read_excel( '你的文件路径.xlsx', sheet_name='目标工作表名', header=start_row - 1, # Pandas的header参数为0索引 nrows=end_row - start_row + 1, usecols=f'{chr(ord("A") + start_col - 1)}:{chr(ord("A") + end_col - 1)}' )
方法3:按区域大小自动识别汇总表
如果汇总表是工作表中数据量最大的连续区域,可计算所有非空区域的大小,取最大的区域作为汇总表:
import pandas as pd from openpyxl import load_workbook def get_all_data_regions(worksheet): regions = [] visited_cells = set() # 遍历所有单元格 for row in range(1, worksheet.max_row + 1): for col in range(1, worksheet.max_column + 1): if (row, col) not in visited_cells and worksheet.cell(row, col).value is not None: # 扩展区域边界 max_row, max_col = row, col # 向下扩展到空行 while max_row + 1 <= worksheet.max_row and worksheet.cell(max_row + 1, col).value is not None: max_row += 1 # 向右扩展到空列 while max_col + 1 <= worksheet.max_column and worksheet.cell(row, max_col + 1).value is not None: max_col += 1 # 标记该区域所有单元格为已访问 for r in range(row, max_row + 1): for c in range(col, max_col + 1): visited_cells.add((r, c)) regions.append((row, max_row, col, max_col)) return regions wb = load_workbook('你的文件路径.xlsx') ws = wb['目标工作表名'] all_regions = get_all_data_regions(ws) # 按区域面积排序,取最大的区域 all_regions.sort(key=lambda x: (x[1]-x[0]+1)*(x[3]-x[2]+1), reverse=True) start_row, end_row, start_col, end_col = all_regions[0] # 读取目标区域 summary_df = pd.read_excel( '你的文件路径.xlsx', sheet_name='目标工作表名', header=start_row - 1, nrows=end_row - start_row + 1, usecols=f'{chr(ord("A") + start_col - 1)}:{chr(ord("A") + end_col - 1)}' )
内容的提问来源于stack exchange,提问作者junfan02
相关产品推荐
相关产品推荐

