【问题标题】:Compare two dataframe columns of sentence strings and create new values for a third frame比较句子字符串的两个数据帧列并为第三帧创建新值
【发布时间】: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


    【解决方案1】:

    我不完全理解你所说的“是”和“和”是什么意思,以及它们为什么会产生错误。但一般来说,如果您尝试根据 A 列和 B 列中的值构造 C 列,最好的方法是使用 lambda 函数。

    def word_match(col_1, col_2):
        # Gather all words in column B to check column A against
        targets = set(col_2.split())
        # For each word in A, if it's in B then 1, else 0
        output = [1 if x in targets else 0 for x in col_1.split()]
        return output
    
    # Create new column, C, whose value on each row is word_match(A, B) on each row
    df['C'] = df.apply(lambda x: word_match(x.A, x.B), axis=1)
    

    希望这会有所帮助!

    【讨论】:

    • 我的意思是,给定一个 B 的例子,例如 ['there are many happy people'] 和 A[there are many happy people who say that they are happy with the government],您可以观察到单词“are”和“happy”出现在短语 B 中,但也出现在指定短语之外的 A 中。这将导致它在 A 中 B 的所需跨度之外返回 1。
    • 我将在这里发布我使用的方法。它虽然涉及正则表达式
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2023-04-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多