当前位置: 首页 > article >正文

python Excel 表读取合并单元格以及清除空格符

读取合并单元格并保留合并信息

  • 读取合并单元格并保留合并信息
  • 清除各单元格的空格和换行符,并去除列名中的空格和换行符

读取合并单元格并保留合并信息

当我们只是使用 pandas 的 read_excel 方法读取 Excel 文件时,我们可能会遇到一个很棘手的问题:合并单元格的信息将会丢失,从而导致我们的数据出现重复或缺失的情况。

在本篇文章中将介绍使用 pandas 正确地读取包含合并单元格的 Excel 表格,支持 xlsx 和 xls。

import pandas as pd
from openpyxl import load_workbook
from xlrd import open_workbook

def read_xlsx(file, sheet_name=None, header=None):
    """读取 xlsx 格式文件。"""
    excel = pd.ExcelFile(load_workbook(file), engine="openpyxl")
    sheet_name = sheet_name or excel.sheet_names[0]
    sheet = excel.book[sheet_name]
    df = excel.parse(sheet_name, header=header)

    for item in sheet.merged_cells:
        top_col, top_row, bottom_col, bottom_row = item.bounds
        base_value = item.start_cell.value
        # 1-based index转为0-based index
        top_row -= 1
        top_col -= 1
        # 由于前面的几行被设为了header,所以这里要对坐标进行调整
        if header is not None:
            top_row -= header + 1
            bottom_row -= header + 1
        df.iloc[top_row:bottom_row, top_col:bottom_col] = base_value
    return df

def read_xls(file, sheet_name=None, header=None):
    """读取 xls 格式文件。"""
    excel = pd.ExcelFile(open_workbook(file, formatting_info=True), engine="xlrd")
    sheet_name = sheet_name or excel.sheet_names[0]
    sheet = excel.book[sheet_name]
    df = excel.parse(sheet_name, header=header)

    # 0-based index
    for top_row, bottom_row, top_col, bottom_col in sheet.merged_cells:
        base_value = sheet.cell_value(top_row, top_col)
        # 由于前面的几行被设为了header,所以这里要对坐标进行调整
        if header is not None:
            top_row -= header + 1
            bottom_row -= header + 1
        df.iloc[top_row:bottom_row, top_col:bottom_col] = base_value
    return df


注:来源https://alanlee.fun/2023/04/27/pandas-read-excel-with-merged-cells/

清除各单元格的空格和换行符,并去除列名中的空格和换行符

在数据处理过程中,字符串中的多余空格和换行符常常会影响数据的整洁性以及后续分析。使用 .replace(‘\n’, ‘’).strip() 可以有效地去除换行符和前后空格,但这并不能解决中间空格的问题。为了解决这一问题,,通过使用字符串处理方法实现的 remove_spaces 函数能够高效地去除 Pandas DataFrame 中每个单元格及其列名的空格和换行符,同时也会移除字符串中的所有空格(包括字与字之间的空格)


def remove_spaces(df):
    """去除 DataFrame 中各单元格的空格和换行符,并去除列名中的空格和换行符。"""
    # 处理列名
    df.columns = [col.replace('\n', '').strip() if isinstance(col, str) else col for col in df.columns]

    # 处理各单元格,去掉所有空格,包括中间的空格和换行符
    return df.apply(lambda col: col.map(lambda x: x.replace('\n', '').replace(' ', '') if isinstance(x, str) else x))


http://www.kler.cn/a/538378.html

相关文章:

  • Qt元对象系统
  • Kafka系列之:定位topic只能保存最新数据的原因
  • 多路文件IO
  • 2025.2.9机器学习笔记:PINN文献阅读
  • PyTorch torch.sign函数介绍
  • Centos执行yum命令报错
  • #渗透测试#批量漏洞挖掘#微商城系统 goods SQL注入漏洞
  • JUnit 5 中获取测试类、测试方法及属性的注解
  • DeepSeek与Vue.js组件开发:解锁AI与前端开发的融合密码
  • 算法兵法全略(译文)
  • 低代码系统-插件功能分析( 某道云)
  • 线性dp-安全序列
  • 指向深度学习的“信息技术”课程单元教学设计方案
  • 数据表中的视图操作
  • 激活函数篇 03 —— ReLU、LeakyReLU、RandomizedLeakkyReLU、PReLU、ELU
  • 如何参与开源项目
  • 33.日常算法
  • Python进阶-在Ubuntu上部署Flask应用
  • iPhone 在华销量大幅下挫
  • STM32启动过程概述
  • Elasticsearch term精确查询无数据
  • Maven 依赖范围与排除
  • 如何训练开源模型成为专业业务模型
  • Racecar Gym 总结
  • DeepSeek训练成本与技术揭秘
  • android中关于CheckBox自定义选中图片选中无效问题