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

使用Pandas拆分含下拉菜单的Excel列并处理拼写错误生成新DataFrame

解决Excel手动输入导致的拼写错误,生成标准化DataFrame

嘿,我来帮你搞定这个拼写错误的问题!用Python的pandas处理这类数据清洗需求简直完美,下面是完全贴合你需求的实现方案:

需求回顾

你需要保留原始的Answers列,同时新增三列:

  • 标准化后的答案列(把错误拼写统一为标准的"Yes"/"No",支持多条目组合)
  • 有效性标记列(判断原始条目是否为合规值)
  • 错误类型列(标记手动输入的错误类型)

具体实现代码

1. 导入库并构造示例数据

先模拟你提供的原始数据:

import pandas as pd

# 模拟你的Excel导入数据
raw_data = {
    "Answers": ["Yes", "No", "no", "noo", "yeah", "Yes, No"]
}
df = pd.DataFrame(raw_data)

2. 添加标准化答案列

我们创建一个映射字典来修正已知的拼写错误,同时兼容合法的多条目组合:

# 定义错误拼写到标准值的映射
spelling_corrections = {
    "no": "No",
    "noo": "No",
    "yeah": "Yes"
}

def standardize_text(answer):
    # 拆分多条目(按", "分割)
    items = [item.strip() for item in answer.split(", ")]
    # 逐个修正拼写,无匹配项则保留原内容
    corrected_items = [spelling_corrections.get(item, item) for item in items]
    # 重新组合成原格式
    return ", ".join(corrected_items)

# 生成标准化列
df["Standardized_Answer"] = df["Answers"].apply(standardize_text)

3. 添加有效性标记列

标记原始条目是否属于你定义的合法值集合:

# 合法值集合(你指定的正确条目)
valid_entries = {"Yes", "No", "Yes, No"}
df["Is_Valid"] = df["Answers"].isin(valid_entries)

4. 添加错误类型列

给错误的手动输入标记具体的错误类型:

def classify_error(answer):
    if answer in valid_entries:
        return None  # 无错误
    answer_lower = answer.lower()
    if answer_lower == "no":
        return "小写拼写错误"
    elif answer_lower == "noo":
        return "多字母拼写错误"
    elif answer_lower == "yeah":
        return "非标准同义词错误"
    else:
        return "未知错误"

df["Error_Type"] = df["Answers"].apply(classify_error)

最终结果

运行上述代码后,你会得到这样的DataFrame:

Answers Standardized_Answer  Is_Valid       Error_Type
0      Yes                  Yes      True             None
1       No                   No      True             None
2       no                   No     False      小写拼写错误
3      noo                   No     False    多字母拼写错误
4     yeah                  Yes     False  非标准同义词错误
5  Yes, No            Yes, No      True             None

扩展说明

如果后续出现新的拼写错误,只需要在spelling_corrections字典和classify_error函数里添加对应的规则即可,非常灵活。要是需要处理更复杂的未知拼写错误,可以考虑使用fuzzywuzzy库做模糊匹配,不过针对你目前给出的错误情况,上面的方案已经足够精准高效了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:40:24