【发布时间】:2021-06-23 22:59:43
【问题描述】:
背景
我有一个 df
import pandas as pd
import nltk
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
df= pd.DataFrame({'ID': [1,2,3],
'Text':['This num dogs and cats is (111)888-8780 and other',
'dont block cow 23 here',
'cat two num: dog and cows here']
})
我也有一个清单
word_list = ['dog', 'cat', 'cow']
还有一个函数应该对 df 的 Text 列与 word_list 进行模糊匹配
def fuzzy(row, word_list):
tweet = row[0]
fuzzy_match = []
for word in word_list:
token_words = nltk.word_tokenize(tweet)
for token in range(0, len(token_words) - 1):
fuzzy_fx = process.extract(word_list[word], token_words[token], limit=100, scorer = fuzz.ratio)
fuzzy_match.append(fuzzy_fx[0])
return pd.Series([fuzzy_match], index = ['Fuzzy_Match'])
然后我加入
df_fuzz = df.join(df.apply(lambda x: fuzzy(x, word_list), axis = 1))
但我得到一个错误
TypeError: expected string or bytes-like object
所需的输出
我想要的输出是 1) 带有 fuzzy 函数输出的新列 Fuzzy_Match
ID Text Fuzzy_Match
0 1 This num dogs and cats is (111)888-8780 and other output of fuzzy 1
1 2 dont block cow 23 here output of fuzzy 2
2 3 cat two num: dog and cows here output of fuzzy 3
问题 我需要做什么才能获得我想要的输出?
【问题讨论】:
-
使用 tweet = row[1] ,目前你在使用 row[0] 时访问 ID。
标签: python pandas text fuzzywuzzy