【发布时间】:2020-08-04 12:04:15
【问题描述】:
在这里,我有两个数据框列。 A 和 B。对于每一行 [i],B 的所有内容都包含在 A 中,现在我正在尝试在 A 中测试 B,并为匹配短语中的所有单词返回 1,对于 A 中的所有其他单词返回 0在短语 B 之外,从而创建一个由 0 和 1 组成的新数据框。
Why would it be competitive, so it's wond... if the teabaggers hadn't ousted Sen
Had he refused to attempt something so partisa... Had he refused to attempt something so partisa...
"This study would then have to be conducted an... This study would then have to be conducted and
预期的数据框。
['0', '0', '0', '0' , '0', '1', '1', '1', '1', '1', '1'........]
我主要尝试了两种方法,但在我在 stackoverflow 上获得的第一种方法中,它是测试 B 中的单个单词而不是 B 列的整个短语,所以我会得到这样的结果
['0', '1', '0', '0' , '0', '1', '1', '1', '1', '1', '1', ........]
其中 B 中的值(例如“is”或“and”)总是容易出现在短语之外并返回错误的结果。
我还尝试了正则表达式,它对单个实例非常有效,但我无法将它应用于数据帧并获得良好的结果。这有点像棘轮作业,它会返回无穷无尽的 1 行或内存不足。
rx = '({})'.format('|'.join(re.escape(el)for el in B))
# Generator to yield replaced sentences, rep_lace is a column of 1's for each word in B
it = (re.sub(rx, rep_lace, sentence)for sentence in A)
# Build list of paired new sentences and old to filter out where not the same
results.append([new_sentence for old_sentence, new_sentence in zip(A, it) if old_sentence != new_sentence])
nw_results = ' '.join([str(elem) for elem in results])
ew_results= nw_results.split(" ")
new_results = ['0' if i is not '1' else i for i in ew_results]
labels =([int(e) for e in new_results])
我希望我给出了足够清楚的解释。
【问题讨论】:
标签: python regex pandas dataframe nlp