首页 > 解决方案 > 检查和删除 Jaro 字符串相似性的 NoneTypes

问题描述

我试图辨别两个字符串之间的字符串相似性(使用 Jaro)。每个字符串都位于我的数据框中的单独列中。

String 1 = df['name_one'] 

String 2 = df['name_two']

当我尝试运行我的字符串相似性逻辑时:

from pyjarowinkler import distance
df['distance'] = df.apply(lambda d: distance.get_jaro_distance(str(d['name_one']),str(d['name_two']),winkler=True,scaling=0.1), axis=1)

我收到以下错误:

 **error: JaroDistanceException: Cannot calculate distance from NoneType (str, str)**

太好了,所以列中有一个无类型,所以我要做的第一件事就是检查这个:

maskone = df['name_one'] == None
df[maskone]

masktwo = df['name_two'] == None
df[masktwo]

这会导致没有找到 None 类型....此时我在这里摸不着头脑,但继续以任何方式清理这两列。

df['name_one'] = df['name_one'].fillna('').astype(str)
df['name_two'] = df['name_two'].fillna('').astype(str) 

然而,我仍然得到:

error: JaroDistanceException: Cannot calculate distance from NoneType (str, str)

我是否正确删除了 NoneTypes?

标签: pythonjaro-winkler

解决方案


问题

问题不完全在于您只是遇到空字符串NoneTypes,这也可能引发此异常,正如您在实现中所看到的那样distance.get_jaro_distance

if not first or not second:
    raise JaroDistanceException("Cannot calculate distance from NoneType ({0}, {1})".format(
        first.__class__.__name__,
        second.__class__.__name__))

选项1

尝试用“NA”替换您的无类型和/或空字符串或从数据集中过滤它们。

选项 2

对可能引发此异常的行使用标志值/距离。在下面的示例中,我将利用999

from pyjarowinkler import distance

df['distance'] = df.apply(lambda d: 999 if not str(d['name_one']) or not str(d['name_two']) else distance.get_jaro_distance(str(d['name_one']),str(d['name_two']),winkler=True,scaling=0.1), axis=1)

推荐阅读