求助:如何用Python将Excel中空行分隔的多行组转换为列
处理Excel中空行分隔的多行数据转列
方法一:基于pandas快速处理(已知每组固定3条数据)
如果确定每组数据都是3条(姓名、年龄、性别),可以先过滤空行再按固定长度分组:
- 先安装依赖(没装的话):
pip install pandas openpyxl
- 代码实现:
import pandas as pd # 读取Excel,不设表头 raw_data = pd.read_excel('你的文件路径.xlsx', header=None) # 提取所有非空数据,转成列表 cleaned_data = raw_data[0].dropna().tolist() # 按每3个元素一组拆分 grouped = [cleaned_data[i:i+3] for i in range(0, len(cleaned_data), 3)] # 转成表格并输出 result = pd.DataFrame(grouped, columns=['姓名', '年龄', '性别']) # 打印成无索引的格式化文本 print(result.to_string(index=False)) # 保存回Excel的话用下面这句 # result.to_excel('输出文件.xlsx', index=False)
方法二:按空行精准拆分组(适合每组数据条数不固定的情况)
如果不确定每组有多少条数据,直接按Excel里的空行来拆分组更稳妥:
from openpyxl import load_workbook import pandas as pd wb = load_workbook('你的文件路径.xlsx') ws = wb.active all_groups = [] current_group = [] # 逐行读取单元格内容 for row in ws.iter_rows(values_only=True): val = row[0] if val is None: # 遇到空行,将当前组存入列表(跳过空组) if current_group: all_groups.append(current_group) current_group = [] else: current_group.append(val) # 处理最后一组数据 if current_group: all_groups.append(current_group) # 转成表格并输出 result = pd.DataFrame(all_groups) print(result.to_string(index=False)) # 保存文件:result.to_excel('输出文件.xlsx', index=False)
说明
- 两种方法都能实现你要的效果,方法一更简洁,方法二更灵活。
- 如果不需要表头,创建DataFrame时可以省略
columns参数。
内容的提问来源于stack exchange,提问作者Roshni
相关产品推荐
相关产品推荐

