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

如何从Python DataFrame中移除数字、特殊字符及非x/o字符?

使用Pandas DataFrame实现表格清洗

步骤1:导入依赖并构造/读取数据

先导入pandas库,若处理实际Excel文件,用pd.read_excel()读取即可;以下是根据你提供的表格构造的示例DataFrame:

import pandas as pd

# 构造示例数据
data = {
    'Input': ['in1', 'in2', 'in3', 'in4'],
    'out1': ['x', 'x', '3', 'x'],
    'out2': ['x', '.', '?', None],
    'out3': ['x', None, None, '/'],
    'out4': ['o', 'c', None, None],
    'out5': ['x', 'v', 'x', None]
}
df = pd.DataFrame(data)

步骤2:定义清洗函数

编写函数过滤单元格内容,仅保留x和o,其余字符(数字、特殊符号、非x/o字母等)全部替换为空:

def clean_cell(value):
    # 处理空值/None场景
    if pd.isna(value):
        return ''
    # 仅保留x、o字符,其余过滤
    cleaned = ''.join([c for c in str(value) if c in ['x', 'o']])
    return cleaned if cleaned else ''

步骤3:对目标列应用清洗逻辑

针对除Input外的所有输出列,批量应用清洗函数:

# 筛选需要清洗的列(所有以out开头的列)
cols_to_clean = [col for col in df.columns if col.startswith('out')]
# 逐单元格应用清洗函数
df[cols_to_clean] = df[cols_to_clean].applymap(clean_cell)

步骤4:查看最终结果

打印处理后的DataFrame,即可得到符合要求的输出:

print(df.to_string(index=False))

输出结果:

Input out1 out2 out3 out4 out5
  in1    x    x    x    o    x
  in2    x                    
  in3                          x
  in4    x                    

补充说明

  • 若Excel包含更多列,只需调整cols_to_clean的筛选规则,确保仅清洗目标列;
  • 若需保留大写的X/O,去掉函数中的字符判断限制即可(当前仅保留小写x/o);
  • 空单元格最终会显示为空字符串,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:15:58