使用 SequenceMatcher Python 在 pandas 中查找所有相似值
Finding all similar values in pandas using SequenceMatcher Python
我正在尝试过滤列中 pandas 中的特定值,但也允许输入错误。我认为使用 SequenceMatcher 是一个很好的解决方案,但我不知道在 DataFrame 中应用它的最佳方法是什么。假设 headers 是 'number' 和 'location'。
df1 = [[1, Amsterdam], [2, amsterdam], [3, rotterdam], [4, amstrdam], [5, Berlin]]
如果我想以特定比例过滤 'amsterdam',假设为 0.6。输出可能是这样的。
df1 = [[1, Amsterdam], [2, amsterdam], [4, amstrdam]]
完成这项工作的最佳方法是什么?我正在考虑使用过滤器选项,但那没有用。我是否需要先 运行 一个应用函数来添加一个包含比率的列,然后才能对其进行过滤?或者有更聪明的方法吗?
df2 = df1[SequenceMatcher(None, location, df1.location).ratio() > 0.6]
你走对了,使用 apply
和 loc
你可以过滤 df。我将比率设置为 0.7,否则鹿特丹也会匹配。
import difflib
import pandas as pd
df = pd.DataFrame([[1, 'Amsterdam'], [2, 'amsterdam'], [3, 'rotterdam'], [4, 'amstrdam'], [5, 'Berlin']])
df.columns = ['number', 'location']
df = df.loc[df.apply(lambda x: difflib.SequenceMatcher(None, 'Amsterdam', x.location).ratio() > 0.7, axis=1)]
print(df)
number location
0 1 Amsterdam
1 2 amsterdam
3 4 amstrdam
我正在尝试过滤列中 pandas 中的特定值,但也允许输入错误。我认为使用 SequenceMatcher 是一个很好的解决方案,但我不知道在 DataFrame 中应用它的最佳方法是什么。假设 headers 是 'number' 和 'location'。
df1 = [[1, Amsterdam], [2, amsterdam], [3, rotterdam], [4, amstrdam], [5, Berlin]]
如果我想以特定比例过滤 'amsterdam',假设为 0.6。输出可能是这样的。
df1 = [[1, Amsterdam], [2, amsterdam], [4, amstrdam]]
完成这项工作的最佳方法是什么?我正在考虑使用过滤器选项,但那没有用。我是否需要先 运行 一个应用函数来添加一个包含比率的列,然后才能对其进行过滤?或者有更聪明的方法吗?
df2 = df1[SequenceMatcher(None, location, df1.location).ratio() > 0.6]
你走对了,使用 apply
和 loc
你可以过滤 df。我将比率设置为 0.7,否则鹿特丹也会匹配。
import difflib
import pandas as pd
df = pd.DataFrame([[1, 'Amsterdam'], [2, 'amsterdam'], [3, 'rotterdam'], [4, 'amstrdam'], [5, 'Berlin']])
df.columns = ['number', 'location']
df = df.loc[df.apply(lambda x: difflib.SequenceMatcher(None, 'Amsterdam', x.location).ratio() > 0.7, axis=1)]
print(df)
number location
0 1 Amsterdam
1 2 amsterdam
3 4 amstrdam