如何在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 header | Another header |
|---|---|
| First(末尾带空格) | row |
| Second | row(末尾带空格) |
输出示例(清理后数据)
| A header | Another header |
|---|---|
| First | row |
| Second | row |
内容的提问来源于stack exchange,提问作者vishakha abnave
相关产品推荐
相关产品推荐

