python - 使用编辑距离替换另一列中的单词

标签 python function pandas dataframe levenshtein-distance

假设我有一个数据框df1:

Sr       A              B                            C
1      rains         It rain there.             It rains there
2      plane         This is a vertical planes  This is a vertical plane
3      tree          Plant a trees              Plant a tree

C是我的预期输出。我需要将 B 列字符串中的每个单词与 A 中的单词进行比较,如果 Levenshtein 距离为 1,则替换它。

我的方法:

import jellyfish as jf
def word_replace(str1):
    comp = #don't know how to store value of column A in this variable.
    for word in str1.split():
        if jf.levenshtein_distance(word,comp) == 1:
           word = comp
        else:
            pass
    return str1

df1['C'] = df1['B'].apply(word_replace)

第二件事,如果A列有像“near miss”这样的双字怎么办?我需要如何修改上面的代码?例如:

 Sr       A              B                            C
  1     near miss        that was a ner mis          that was a near miss

最佳答案

您在一个问题中提出了两个问题,这在 Stack Overflow 上绝不是一个好主意。我只是回答你的第一个问题,如果你想让别人看你的第二个问题那么我建议你专门写一个新问题。

pd.DataFrame.apply可以跨行或跨列工作,您希望单独处理每一行,因此必须传递 axis=1 关键字参数。

下面是一些解决您问题的代码,它使用 list comprehension利用ternary operator选择需要替换的单词。然后使用str.join()将该列表连接在一起。 。

最初,您的代码正在迭代分割字符串,但这不起作用 as you cannot modify them as you are iterating over the list 。它还假设函数的输入是一个字符串,这是不正确的,因为它将是一个 pandas.Series 对象。

这是一段简化的代码,没有考虑标点符号之类的东西,我将其作为练习留给读者。

import pandas as pd
import jellyfish as jf

data1 =  {'A':['rains','plane','tree'],'B':['It rain there','This is a vertical planes','Plant a trees']}
df1 = pd.DataFrame(data1)

def word_replace(row):
    comp = row['A']
    str1 = row['B']

    out = ' '.join([comp if jf.levenshtein_distance(word, comp) == 1
                    else word for word in str1.split()])
    return out

df1['C'] = df1.apply(word_replace, axis=1)

关于python - 使用编辑距离替换另一列中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24078723/

相关文章:

Python:如何保存训练数据集

python - 使用 cython 加速 numpy 矩阵乘法

excel - 将 find LastRow 代码转换为函数

c++ - C++ 中 main 的正确声明是什么?

function - Tampermonkey 按类单击按钮

python - 使用 Pandas 拆分数据

python - 合并避免重复的列,但只保留一个重复的列

python - Pandas Dataframe - 如何将多行合并为一行

python - 将 pandas 数据框转换为 pandas 系列

python - 基于前一行的 Pandas 数据框列