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

替换keywords为keyw列表时出现TypeError错误排查

替换keywords为keyw触发TypeError的原因与解决

问题场景

现有代码通过提取类别关键词匹配DataFrame列内容,生成新的Cuisine列:

keywords = cat.value_counts().keys().tolist()
nums = Counter(cat).most_common()
keyw = ([num for num, _ in nums])

def findcuisine(col):
  for word in keywords:
    if word in col:
      return word

df2['Cuisine'] = df2['categories'].apply(findcuisine)
yelp_df = df2.drop(columns=['A', 'B','C','D'])

其中cat是DataFrame列,内容为['Pizza', 'Sandwiches', 'Mexican', ...]这类字符串,但可能存在缺失值。将函数中的keywords替换为keyw后,触发报错:

TypeError: 'in <string>' requires string as left operand, not NoneType

报错根源

  • keywords由cat.value_counts().keys().tolist()生成:pandas的value_counts()默认开启dropna=True,会自动忽略列中的缺失值(None/NaN),因此keywords列表中只有有效字符串类别。
  • keyw由Counter(cat).most_common()推导:Python的Counter会统计列中所有元素,包括None值(如果cat列存在缺失),导致keyw列表混入None元素。
  • 当函数遍历keyw遇到None时,执行if None in col操作,因in要求左操作数为字符串,而None不属于字符串类型,直接触发TypeError。

修复方案

方案1:生成keyw时过滤None

修改keyw的推导逻辑,排除None元素:

nums = Counter(cat).most_common()
keyw = [num for num, _ in nums if num is not None]

方案2:统计前先清理缺失值

先剔除cat列的缺失值,再用Counter统计:

nums = Counter(cat.dropna()).most_common()
keyw = [num for num, _ in nums]

方案3:函数内跳过None元素

若不想修改keyw生成逻辑,可在匹配函数中增加None判断:

def findcuisine(col):
  for word in keyw:
    if word is None:
      continue
    if word in col:
      return word

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:31:05