【问题标题】:Count the (total) number of special words in large pandas df计算大熊猫df中特殊词的(总)数
【发布时间】:2022-01-10 21:17:58
【问题描述】:

我有很大的 df 文本:

target = [['cuantos festivales conciertos sobre todo persona perdido esta pandemia'],
['existe impresión estar entrando últimos tiempos pronto tarde mayoría vivimos sufriremos'],
['pandemia sigue hambre acecha humanidad faltaba mueren inundaciones bélgica alemania'],
['nombre maría ángeles todas mujeres sido asesinadas hecho serlo esta pandemia lugares de trabajo']]

还有4组词like:

words1 = ['festivales', 'pandemia', 'lugares de trabajo', 'mueren', 'faltaba']
words2 = ['persona ', 'faltaba', 'entrando', 'sobre']

此外,集合中的单词可能包含空格,例如“lugares de trabajo”。

我需要计算列表中的单词在总和的每一行中出现了多少次(我不需要其中一个单词出现了多少次) 所以结果 df 看起来像:

  word_set1 word_set_2
1     1          1
2     0          1
3     2          1
4     1          0

我尝试了这个计数(然后我打算只总结结果)

for terms in words1:
    df[str(terms)] = map(lambda x: x.count(str(terms)), target['tokenized'])

但是得到了

TypeError: 'map' 类型的对象没有 len()

【问题讨论】:

  • 两个列表中是否都存在“faltaba”?

标签: python pandas word-count


【解决方案1】:

我们可以使用str.count方法得到预期的结果:

df['word_set1'] = df['text'].str.count('|'.join(words1))
df['word_set2'] = df['text'].str.count('|'.join(words2))

输出:

    text                                                word_set1   word_set2
0   cuantos festivales conciertos sobre todo perso...   2           2
1   existe impresión estar entrando últimos tiempo...   0           1
2   pandemia sigue hambre acecha humanidad faltaba...   3           1
3   nombre maría ángeles todas mujeres sido asesin...   2           0

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2018-03-28
    相关资源
    最近更新 更多