在数据框列中按组分组,使用Python Pandas NLTK频率分布来对分词后的单词进行统计。

3

I have the following sample dataframe:

No  category    problem_definition
175 2521       ['coffee', 'maker', 'brewing', 'properly', '2', '420', '420', '420']
211 1438       ['galley', 'work', 'table', 'stuck']
912 2698       ['cloth', 'stuck']
572 2521       ['stuck', 'coffee']

problem_definition字段已使用停用词进行分词处理。

我想创建一个频率分布,输出另一个Pandas数据框:

1)包含problem_definition中每个单词的出现频率 2)包含problem_definition和category字段中每个单词的出现频率

示例所需输出如下(针对情况1):

text       count
coffee     2
maker      1
brewing    1
properly   1
2          1
420        3
stuck      3
galley     1
work       1
table      1
cloth      1

以下是第二种情况所需的样本输出:

category    text       count
2521        coffee     2
2521        maker      1
2521        brewing    1
2521        properly   1
2521        2          1
2521        420        3
2521        stuck      1
1438        galley     1
1438        work       1
1438        table      1
1438        stuck      1
2698        cloth      1
2698        stuck      1

我尝试了下面的代码来实现1):
from nltk.probability import FreqDist
import pandas as pd

fdist = FreqDist(df['problem_definition_stopwords'])

类型错误:不可散列类型:'list'

我不知道如何完成第二个任务


你期望的 counts 是否按 category 分组? - BernardL
是的,按类别分组的不同单词计数 - PineNuts0
2个回答

2

使用unnesting,我逐步介绍了几种解决此类问题的方法。为了好玩,我在这里链接了问题

unnesting(df,['problem_definition'])
Out[288]: 
  problem_definition   No  category
0             coffee  175      2521
0              maker  175      2521
0            brewing  175      2521
0           properly  175      2521
0                  2  175      2521
0                420  175      2521
0                420  175      2521
0                420  175      2521
1             galley  211      1438
1               work  211      1438
1              table  211      1438
1              stuck  211      1438
2              cloth  912      2698
2              stuck  912      2698
3              stuck  572      2521
3             coffee  572      2521

对于情况2,只需进行常规的groupby+size操作即可。

unnesting(df,['problem_definition']).groupby(['category','problem_definition']).size()
Out[290]: 
category  problem_definition
1438      galley                1
          stuck                 1
          table                 1
          work                  1
2521      2                     1
          420                   3
          brewing               1
          coffee                2
          maker                 1
          properly              1
          stuck                 1
2698      cloth                 1
          stuck                 1
dtype: int64

关于案例1的value_counts

unnesting(df,['problem_definition'])['problem_definition'].value_counts()
Out[291]: 
stuck       3
420         3
coffee      2
table       1
maker       1
2           1
brewing     1
galley      1
work        1
cloth       1
properly    1
Name: problem_definition, dtype: int64

自定义函数

def unnesting(df, explode):
    idx=df.index.repeat(df[explode[0]].str.len())
    df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
    df1.index=idx
    return df1.join(df.drop(explode,1),how='left')

谢谢,我收到了“unnesting未定义”的错误信息...我需要导入一个包来使用unnesting吗? - PineNuts0
@PineNuts0 你的意思是 unnesting(df,['problem_definition'])['problem_definition'].value_counts() 出了问题吗? - BENY
我是说 unnesting(df,['problem_definition']) 出现了错误。 - PineNuts0
还有一个问题:我想让“counts”字段按类别从大到小排序...? - PineNuts0
使用sort_indexsort_values进行排序检查 @PineNuts0 - BENY
显示剩余5条评论

0

您还可以按类别展开列表,然后进行groupbysize操作。

import pandas as pd
import numpy as np

df = pd.DataFrame( {'No':[175,572],
                    'category':[2521,2521],
                    'problem_definition': [['coffee', 'maker', 'brewing', 'properly', '2', '420', '420', '420'],
                                          ['stuck', 'coffee']]} )

c = df.groupby('category')['problem_definition'].agg('sum').reset_index()

lst_col = 'problem_definition'

c = pd.DataFrame({
      col:np.repeat(c[col].values, c[lst_col].str.len())
      for col in c.columns.drop(lst_col)}
    ).assign(**{lst_col:np.concatenate(c[lst_col].values)})[c.columns]

c.groupby(['category','problem_definition']).size()
>>
category  problem_definition
2521      2                     1
          420                   3
          brewing               1
          coffee                2
          maker                 1
          properly              1
          stuck                 1
dtype: int64

或者你也可以使用计数器来帮助你按 category 分组存储计数值:

import pandas as pd
import numpy as np
from collections import Counter

df = pd.DataFrame( {'No':[175,572],
                    'category':[2521,2521],
                    'problem_definition': [['coffee', 'maker', 'brewing', 'properly', '2', '420', '420', '420'],
                                          ['stuck', 'coffee']]} )

c = df.groupby('category')['problem_definition'].agg('sum').reset_index()
c['problem_definition'] = c['problem_definition'].apply(lambda x: Counter(x).items())

lst_col = 'problem_definition'

s = pd.DataFrame({
      col:np.repeat(c[col].values, c[lst_col].str.len())
      for col in c.columns.drop(lst_col)}
    ).assign(**{'text':np.concatenate(c[lst_col].apply(lambda x: [k for (k,v) in x]))}
    ).assign(**{'count':np.concatenate(c[lst_col].apply(lambda x: [v for (k,v) in x]))} )

s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接