我有一个系列,它有近4000个不同的字符串,以及一个包含两个系列的数据帧。我试图遍历每个字符串,找到那些字符串中与其他数据帧的第二系列中的任何单词匹配的单词。如果它们匹配,则将字符串中的单词替换为数据帧中第一个序列中的单词。
这是我想要做的一个例子。
拆分成列表的示例字符串。
0 [I, like, the, acura, vigor]数据框。
acura integra
0 acura legend
1 acura vigor
2 acura rlx
3 acura ilx
4 acura mdx因此,该字符串将“vigor”替换为“acura”。
[I, like, the, acura, acura]发布于 2020-09-12 05:05:14
实际上,数据帧方法似乎有点过度工程化。我建议使用简单的正则表达式:
import re
txt = 'this is a test text to replace legend, 2nd legend and fox with acura'
wordlist = ['fox', 'legend']
for word in wordlist:
txt = re.sub(word,'acura',txt)
print(txt)如果您需要进一步步骤的数据帧,您仍然可以使用正则表达式示例作为基础。
发布于 2020-09-12 06:43:02
让我们把这个问题分解一下。
w,w 中的相应替换
作为代码,
mylist = ['I', 'like', 'the', 'acura', 'vigor']
# df = the dataframe, with columns 'replacement' and 'lookup'
for index, word in enumerate(mylist):
matched_row = df.loc[df['lookup'] == word]
if not matched_row.empty:
mylist[index] = matched_row.iloc[0]['replacement']https://stackoverflow.com/questions/63853016
复制相似问题