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

使用Pandas结合NLTK清理DataFrame中OneCol列失败求助

原有代码错误原因

  • 遍历写法中df_US['Result'].iloc.append(value)是错误用法:Pandas 已弃用Series.append方法,且循环中直接对整列df_US['Result']赋值会重复覆盖整列数据,无法实现逐行判断存储的效果
  • 注释的apply写法逻辑错误:lambda中接收的x是OneCol列的元素/Series对象,本身不具备words属性,无法直接调用nltk的词库方法
  • 直接用words.words()做成员查询速度极慢:该方法返回的是列表,成员查询时间复杂度为O(n),数据量大时性能极差

修复方案

第一步:提前预处理词库

先把nltk词库转为集合,将查询复杂度降到O(1),首次使用需先下载词库:

import pandas as pd
import nltk
from nltk.corpus import words

# 首次运行需执行下载,后续运行可注释
nltk.download('words')
# 转为集合加速查询
valid_en_words = set(words.words())

第二步:按需求生成结果

如果需要保留所有行,符合要求的OneCol值存入Result列、不符合的留空:

# 如果需要忽略大小写匹配,可改为x.lower() in valid_en_words
df_US['Result'] = df_US['OneCol'].apply(lambda x: x if x in valid_en_words else pd.NA)

如果仅需要保留OneCol为合法英文单词的行,直接过滤即可:

df_filtered = df_US[df_US['OneCol'].isin(valid_en_words)].copy()

数据样例参考:
数据样例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 01:39:02