【问题标题】:Compare two Dataframes of sentences and return a third one比较两个句子数据框并返回第三个
【发布时间】:2020-04-20 16:05:25
【问题描述】:

我想比较两个长数据框列的句子,并返回第三个数据框,如下所示。 快照如下所示。

我的第一种方法是冗长的,只适用于单个实例,但是当我将它应用于数据框时失败了。可以在上一个问题中找到。

逻辑是针对 c1 和 c2 中的单词,新值 =1,仅针对 c1 中的单词,值设置为零。


sentences = tra_df['Sent1']
context = tra_df['Sent2']
Sent1[0] = "I am completely happy with the plan you have laid out today"
Sent2[0] = 'the plan you have laid out today'
c3 = ['0', '0', '0', '0' , '0', '1', '1', '1', '1', '1', '1'] 

【问题讨论】:

  • 我看到的都是字符串和列表,数据框在哪里?
  • 它实际上是一个数据框,但我显示了字符串和列表以便显示数据类型的快照
  • @jorijinsmit 我现在已经澄清了

标签: python pandas python-re


【解决方案1】:

根据我对您的问题的理解,这是解决方案。

def get_common_words(c1, c2):
    res = [0]*len(c1.split())
    for idx, existing_word in enumerate(c1.split()):
        if existing_word in c2.split():
            res[idx] = 1
    return res

get_common_words(c1, c2)

如果你想让它适用于 pandas 数据框

def get_common_words_df(row):
   c1 = row['Sent1']
   c2 = row['Sent2']
   return get_common_words(c1, c2)


df['sent3'] = df.apply(get_common_words_df, axis=1)

你可以优化很多

【讨论】:

  • 感谢您的澄清,但我不太明白这两个功能如何协同工作。我有一个包含 3000 行 Sent1 和 Sent2 的 DataFrame 列,我想在不手动调用函数的每一行的情况下迭代它们
  • apply 也会这样做。请查看文档
  • 此解决方案还遗漏了另一件事。 sent 1 中唯一应该交换的部分是 sent 2 的短语的确切部分。如果我通过添加“我对你今天制定的计划完全满意”来修改 sent1,我添加的额外单词就会出现作为“1”而不是“0”
猜你喜欢
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 2019-02-08
  • 2020-08-04
  • 1970-01-01
  • 2020-07-31
  • 2019-03-17
相关资源
最近更新 更多