如何从 pandas 数据框中创建一袋单词 [英] How to create a bag of words from a pandas dataframe

查看:57
本文介绍了如何从 pandas 数据框中创建一袋单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数据框

    CATEGORY    BRAND
0   Noodle  Anak Mas
1   Noodle  Anak Mas
2   Noodle  Indomie
3   Noodle  Indomie
4   Noodle  Indomie
23  Noodle  Indomie
24  Noodle  Mi Telor Cap 3
25  Noodle  Mi Telor Cap 3
26  Noodle  Pop Mie
27  Noodle  Pop Mie
...

我已经确保df类型是字符串,我的代码是

I already make sure that df type is string, my code is

df = data[['CATEGORY', 'BRAND']].astype(str)
import collections, re
texts = df
bagsofwords = [ collections.Counter(re.findall(r'\w+', txt))
            for txt in texts]
sumbags = sum(bagsofwords, collections.Counter())

当我打电话

sumbags

输出为

 Counter({'BRAND': 1, 'CATEGORY': 1})

除标题外,我希望所有数据都包含在sumbag中,以使诸如此类的内容清晰可见

I want all of the data count in sumbags, except the title, to make it clear something like

Counter({'Noodle': 10, 'Indomie': 4, 'Anak': 2, ....}) # because it is bag of words

我需要每1个字数

推荐答案

IIUIC,使用

选项1] 脾气暴躁的flattensplit

In [2535]: collections.Counter([y for x in df.values.flatten() for y in x.split()])
Out[2535]:
Counter({'3': 2,
         'Anak': 2,
         'Cap': 2,
         'Indomie': 4,
         'Mas': 2,
         'Mi': 2,
         'Mie': 2,
         'Noodle': 10,
         'Pop': 2,
         'Telor': 2})

选项2] 使用value_counts()

In [2536]: pd.Series([y for x in df.values.flatten() for y in x.split()]).value_counts()
Out[2536]:
Noodle     10
Indomie     4
Mie         2
Pop         2
Anak        2
Mi          2
Cap         2
Telor       2
Mas         2
3           2
dtype: int64

选项3] 使用stackvalue_counts

In [2582]: df.apply(lambda x: x.str.split(expand=True).stack()).stack().value_counts()
Out[2582]:
Noodle     10
Indomie     4
Mie         2
Pop         2
Anak        2
Mi          2
Cap         2
Telor       2
Mas         2
3           2
dtype: int64


详细信息


Details

In [2516]: df
Out[2516]:
   CATEGORY           BRAND
0    Noodle        Anak Mas
1    Noodle        Anak Mas
2    Noodle         Indomie
3    Noodle         Indomie
4    Noodle         Indomie
23   Noodle         Indomie
24   Noodle  Mi Telor Cap 3
25   Noodle  Mi Telor Cap 3
26   Noodle         Pop Mie
27   Noodle         Pop Mie

这篇关于如何从 pandas 数据框中创建一袋单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆