首页 > 解决方案 > 如果文本包含在另一个数据框中,则使用二进制指定标记行

问题描述

我正在研究挖掘调查数据。我能够标记某些关键字的行:

survey['Rude'] = survey['Comment Text'].str.contains('rude', na=False, regex=True).astype(int)

现在,我想标记任何包含名称的行。我有另一个包含美国常见名称的数据框。这是我认为可行的方法,但它没有标记任何行,并且我已验证名称确实存在于“评论文本”中

for row in survey:   
    for word in survey['Comment Text']:
        survey['Name'] = 0
        if word in names['Name']:
            survey['Name'] = 1

标签: pythonpandas

解决方案


您没有正确循环浏览该系列。 for row in survey:循环遍历survey. for word in survey['Comment Text']:循环通过注释字符串。survey['Name'] = 0创建一列 all 0s

您可以使用set intersectionsapply()来避免所有循环行:

    survey = pd.DataFrame({'Comment_Text':['Hi rcriii',
                                           'Hi yourself stranger',
                                           'say hi to Justin for me']})
    names = pd.DataFrame({'Name':['rcriii', 'Justin', 'Susan', 'murgatroyd']})
    s2 = set(names['Name'])

    def is_there_a_name(s):
        s1 = set(s.split())
        if len(s1.intersection(s2))>0:
            return 1
        else:
            return 0

    survey['Name'] = survey['Comment_Text'].apply(is_there_a_name)

    print(names)
    print(survey)

         Name
0      rcriii
1      Justin
2       Susan
3  murgatroyd
              Comment_Text  Name
0                Hi rcriii     1
1     Hi yourself stranger     0
2  say hi to Justin for me     1

作为奖励,返回len(s1.intersection(s2))以获取每行的匹配数。


推荐阅读