如何在数据框中计算特定单词的实例?

2024-09-26 22:10:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算这些ngram在一个装满文章的数据帧列(df.content)中出现的次数。 我的数据帧是:

enter image description here

我的ngram列表如下:

enter image description here

df_ngrams中的'value'列显示了特定ngram在df.content中出现的次数,但我想计算每一篇文章的次数

我已经试过了:

ngrams_count = ['u s', 'president trump', 'donald trump', 'united states', 'white house', 'new york', 'hillary clinton', 'fox news', 'donald trumps', 'president donald']
count = 0
articleCount = 0

for i in df.content:
    articleCount += 1
    for j in ngrams_count:
        if j in i:
            count = i.find(j)
        print ("article ", articleCount, "has ", count, " instances of ngram ", j)
        counts = 0

Tags: 数据indf列表forcount文章content
2条回答

试试这个:

df["content"].apply(lambda x: pd.Series({el: x.count(el) for el in ngrams_count})).sum()

样本输出:

>>> lst
['dfo', 'a', 'd0', 'do']
>>> df
   idx                               cnt
0    1    a fero eo dk v,e oe pero c, el
1    2          fdo pr ck ,,w ld. dp dfp
2    3      40fk ldf mdl sdm dfl mfd dfl
3    4     dov övdke dmc kfdoe flgp dofr
4    5             fdk0v do fdok dlw pds
5    6               dfo df0 ld cödp wpl
6    7              fdo d0 dl dfl dflre
7    8           dfo dfp 0er a na bab sb
8    9           fdo 0fd ldm cd. wdld so
9   10  reo dodf fd0fd dlss0 d0dsl sdl s
>>> df["cnt"].apply(lambda x: pd.Series({el: x.count(el) for el in lst})).sum()
dfo    2
a      4
d0     3
do     9
dtype: int64

不要试图提供不同的方法,也不要利用你的方法,这里是你需要的改变。你需要数一数一克发生的次数,而不是找不到它。find()只提供找到它的索引,如果找不到文本,则返回-1(这不是您想要的):

for i in df.content:
    articleCount += 1
    for j in ngrams_count:
        count = i.count(j)
        print ("article ", articleCount, "has ", count, " instances of ngram ", j)

相关问题 更多 >

    热门问题