You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jupyter Notebook中用Pandas去除Excel表格数据末尾空格

在Jupyter Notebook中用Pandas清除Excel表格所有数据末尾空格
  • 安装并导入依赖库
    先确保安装好处理Excel所需的工具包:

    pip install pandas openpyxl
    

    在Jupyter Notebook中导入库:

    import pandas as pd
    
  • 读取目标Excel文件
    假设待处理的Excel文件名为raw_data.xlsx,读取为DataFrame:

    df = pd.read_excel('raw_data.xlsx', engine='openpyxl')
    
  • 批量清除单元格末尾空格
    遍历所有单元格,仅对字符串类型内容执行末尾空格清除操作:

    def clean_trailing_space(cell):
        if isinstance(cell, str):
            return cell.rstrip()
        return cell
    
    df_cleaned = df.applymap(clean_trailing_space)
    

    也可以用更简洁的方式,只针对字符串类型的列处理:

    string_columns = df.select_dtypes(include=['object']).columns
    df[string_columns] = df[string_columns].apply(lambda col: col.str.rstrip())
    
  • 保存清理后的表格
    将处理完成的数据保存为新的Excel文件(或覆盖原文件):

    df_cleaned.to_excel('cleaned_data.xlsx', index=False, engine='openpyxl')
    

输入示例(原表格数据)

A headerAnother header
First(末尾带空格)row
Secondrow(末尾带空格)

输出示例(清理后数据)

A headerAnother header
Firstrow
Secondrow

内容的提问来源于stack exchange,提问作者vishakha abnave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:09:16