如何用Pandas处理Excel中含合并单元格的物种表头?
解决合并单元格Excel表头重命名问题
问题分析
你当前代码的问题在于:
- 第二次读取时指定
header=1,导致pandas将重复的子列名(如多个物种下的Point_1)自动添加.1、.2后缀 - 循环中的列切片范围错误,导致物种名与子列名的对应关系混乱,最终生成了
Specie_2_Specie_1_Point_1.1这类嵌套错误的列名
正确实现方案
方案1:利用多级表头自动拼接列名
直接读取Excel的前两行作为多级表头,再将两级表头拼接成目标格式:
import pandas as pd # 读取带合并单元格的表头,header=[0,1]表示用前两行构建多级表头 df = pd.read_excel("/content/drive/MyDrive/Pollens.xlsx", sheet_name="Jun", header=[0, 1]) # 拼接多级表头为目标列名 new_columns = [] for col_tuple in df.columns: # 处理前两列(Data、Hour) if col_tuple[0] in ("Data", "Hour"): new_columns.append(col_tuple[0]) else: # 处理合并单元格的空表头,继承上一个物种名 specie = col_tuple[0] if pd.notna(col_tuple[0]) else new_columns[-1].split("_")[0] sub_col = col_tuple[1] new_columns.append(f"{specie}_{sub_col}") # 重命名列并查看结果 df.columns = new_columns print(df.columns) df.head()
方案2:手动构建列名
如果不想用多级表头,可以先读取表头行,手动匹配物种名和子列名:
import pandas as pd # 分别读取两行表头 header_top = pd.read_excel("/content/drive/MyDrive/Pollens.xlsx", sheet_name="Jun", nrows=0).columns header_bottom = pd.read_excel("/content/drive/MyDrive/Pollens.xlsx", sheet_name="Jun", header=0, nrows=0).columns # 处理合并单元格,补全每个子列对应的物种名 specie_list = [] current_specie = None for col in header_top[2:]: if pd.notna(col): current_specie = col specie_list.append(current_specie) # 构建完整列名 new_columns = list(header_top[:2]) # 保留Data、Hour for sp, sub_col in zip(specie_list, header_bottom[2:]): new_columns.append(f"{sp}_{sub_col}") # 读取数据并设置新列名 df = pd.read_excel("/content/drive/MyDrive/Pollens.xlsx", sheet_name="Jun", header=2) df.columns = new_columns print(df.columns) df.head()
效果说明
两种方案都能生成Specie_1_Point_1、Specie_1_Média、Specie_2_Point_1这类符合需求的列名,不会出现嵌套重复的问题。
内容的提问来源于stack exchange,提问作者Vitor Fernandes
相关产品推荐
相关产品推荐

