我有一个问题,我想计算数据帧中的唯一单词,但不幸的是,它只计算第一句话.

                          text
0  hello is a unique sentences
1         hello this is a test
2              does this works
import pandas as pd
d = {
    "text": ["hello is a unique sentences",
             "hello this is a test", 
             "does this works"],
}
df = pd.DataFrame(data=d)


from collections import Counter

# Count unique words
def counter_word(text_col):
    print(len(text_col.values))
    count = Counter()
    for i, text in enumerate(text_col.values):
        print(i)
        for word in text.split():
            count[word] += 1
        return count

counter = counter_word(df['text'])
len(counter)

推荐答案

我认为更简单的方法是通过空格连接值,然后拆分为单词和计数:

counter = Counter((' '.join(df['text'])).split())

print (counter)
Counter({'hello': 2, 'is': 2, 'a': 2, 'this': 2, 'unique': 1, 'sentences': 1, 'test': 1, 'does': 1, 'works': 1})

Python相关问答推荐

使用plotnine和Python构建地块

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

韦尔福德方差与Numpy方差不同

通过Selenium从页面获取所有H2元素

avxspan与pandas period_range

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

在np数组上实现无重叠的二维滑动窗口

如何在UserSerializer中添加显式字段?

Scrapy和Great Expectations(great_expectations)—不合作

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

不允许访问非IPM文件夹

在输入行运行时停止代码

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

如何将返回引用的函数与pybind11绑定?

为罕见情况下的回退None值键入

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

将字节序列解码为Unicode字符串

Matplotlib中的曲线箭头样式

根据边界点的属性将图划分为子图