获取计数的总和并减去python

时间:2018-10-17 08:02:50

标签: python pandas lambda split count

我想获得关键词的总和减去相反单词的总和,然后返回句子。这是我所拥有的:

df = pd.read_excel('C:/Test.xlsx')
df.drop_duplicates(['Content'],inplace=True)
a = df['Content'].str.lower()
searchfor =['heating','lagging',... and 100+words]
opposite = ['no heating','no lagging',...and 100+words]
b = a[a.str.contains(searchfor)]
c = a[a.str.contains(opposite)]

例如,在“内容”中,我有几句话[“电话不加热也不滞后”,“电话不加热不滞后” ...] 第一句话包含searchfor中的2个单词和相反的1个单词。第二句话包含来自searchfor的2个单词和来自反面的2个单词。我想做的是计算搜索和相反两个词的总和。然后((搜索中的关键字总和减去相反的关键字总和。如果为零,则返回句子。

这是我尝试过的方法,但是它不起作用

d = c.str.split()
def check_it(sentences):
   find_words = []
   for word in searchfor:
        if word in sentences:
            find_words.append(d.count(word))
   return sentences
d = d.apply(lambda x:check_it(x))

,然后再进行一次def检查。它不会起作用,并给我错误。

如果有人可以帮助我,我将很感激

1 个答案:

答案 0 :(得分:2)

[使用Python 3,需要熊猫]

很高兴看到您的实际数据样本,但是,我假设您的数据框将具有如下所示的样本(如果不是这种情况,请更正我):

+-----+----------------------------------------+
|index|content                                 |
+-----+----------------------------------------+
|0    |the phone is heating but not lagging    |
|1    |the phone is not heating and not lagging|
+-----+----------------------------------------+

我们现在创建一个用作lambda的函数,如下所示:

def get_difference_of_keywords(content_string, searchfor, opposite):
    searchfor_matches = len([keyword for keyword in searchfor if keyword in content_string])
    opposite_matches = len([keyword for keyword in opposite if keyword in content_string])
    difference = searchfor_matches - opposite_matches
    if not difference == 0:
        return str(difference)
    return content_string

这使用python的列表推导来获取'searchfor'和'opposite'的匹配数,然后返回差异(如果差异不为零),或者返回原始输入语句(如果差异为零)。

注意:我已将返回的数字从零以上的差异转换为字符串,以确保新列中没有混合的数据类型。这是可选的,取决于您。

然后我们应用以上内容:

df['get_difference_result'] = df.apply(
    lambda row: get_difference_of_keywords(row['content'], searchfor, opposite),
    axis=1
)

这将导致以下结果:

+-----+----------------------------------------+----------------------------------------+
|index|content                                 |get_difference_result                   
|
+-----+----------------------------------------+----------------------------------------+
|0    |the phone is heating but not lagging    |1                                       |
|1    |the phone is not heating and not lagging|the phone is not heating and not lagging|
+-----+----------------------------------------+----------------------------------------+