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

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

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

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

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

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

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

import pandas as pd
from openpyxl import load_workbook
from xlrd import open_workbookdef 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.boundsbase_value = item.start_cell.value# 1-based index转为0-based indextop_row -= 1top_col -= 1# 由于前面的几行被设为了header,所以这里要对坐标进行调整if header is not None:top_row -= header + 1bottom_row -= header + 1df.iloc[top_row:bottom_row, top_col:bottom_col] = base_valuereturn dfdef 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 indexfor 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 + 1bottom_row -= header + 1df.iloc[top_row:bottom_row, top_col:bottom_col] = base_valuereturn 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.lryc.cn/news/532942.html

相关文章:

  • 额外题目汇总2-链表
  • C#控件开发6—指示灯
  • 探索从传统检索增强生成(RAG)到缓存增强生成(CAG)的转变
  • 【学习总结|DAY036】Vue工程化+ElementPlus
  • 【GitHub】GitHub 2FA 双因素认证 ( 使用 Microsoft Authenticator 应用进行二次验证 )
  • c# 2025/2/7 周五
  • 蓝桥杯思维训练(五)
  • I.MX6ULL 中断介绍下
  • Elasticsearch 生产集群部署终极方案
  • Python用langchain、OpenAI大语言模型LLM情感分析苹果股票新闻数据及提示工程优化应用...
  • 【正点原子K210连载】第六十七章 音频FFT实验 摘自【正点原子】DNK210使用指南-CanMV版指南
  • Centos Ollama + Deepseek-r1+Chatbox运行环境搭建
  • ReactNative进阶(五十九):存量 react-native 项目适配 HarmonyOS NEXT
  • go并发和并行
  • 一种解决SoC总线功能验证完备性的技术
  • Web3 与区块链:开启透明、安全的网络新时代
  • c#中Thread.Join()方法的经典示例
  • 深入了解越权漏洞:概念、危害与防范
  • MySQL 数据库编程-C++
  • dl学习笔记(9):pytorch数据处理的完整流程
  • wps中的vba开发
  • 力扣 LCR 078 合并K个升序链表
  • 【hive】记一次hiveserver内存溢出排查,线程池未正确关闭导致
  • React Native 开发 安卓项目构建工具Gradle的配置和使用
  • IntelliJ IDEA新版本的底部version control(或git)里local change窗口显示配置修改详细教程
  • MySQL三大日志——binlog、redoLog、undoLog详解
  • MCU应用踩坑笔记(ADC 中断 / 查询法)
  • 32.日常算法
  • 通过docker安装部署deepseek以及python实现
  • 批量提取word表格数据到一个excel