python - 计算每行的字数

标签 python string python-3.x pandas dataframe

我正在尝试在 DataFrame 中创建一个新列,其中包含相应行的字数。我正在寻找单词总数,而不是每个不同单词的频率。我以为会有一种简单/快速的方法来完成这项常见任务,但在谷歌搜索并阅读了一些 SO 帖子( 1234 )后,我被卡住了。我已经尝试了链接的 SO 帖子中提出的解决方案,但返回了很多属性错误。

words = df['col'].split()
df['totalwords'] = len(words)

结果

AttributeError: 'Series' object has no attribute 'split'

f = lambda x: len(x["col"].split()) -1
df['totalwords'] = df.apply(f, axis=1)

结果

AttributeError: ("'list' object has no attribute 'split'", 'occurred at index 0')

最佳答案

str.split + str.len

str.len 适用于任何非数字列。

df['totalwords'] = df['col'].str.split().str.len()

str.count

如果您的单词是单个空格分隔的,您可以简单地计算空格加 1。

df['totalwords'] = df['col'].str.count(' ') + 1

列表理解

这比你想象的要快!

df['totalwords'] = [len(x.split()) for x in df['col'].tolist()]

关于python - 计算每行的字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49984905/

相关文章:

python - PySpark ML : OnevsRest strategy for LinearSVC

c - 如何将字符串数组传递给 C 中的函数?

python-3.x - 在 Pandas 数据框行中仅保留第一组非 nan 值

Python 模拟 : Mocking a function inside the function I'm testing

python - 如何使用 Matplotlib 在不同的投影中绘制 Tissot 指标线?

python - 我的本地 Eclipse 可以在 Docker 容器中安装 Access 库吗?

C 写入文件的可重复选择问题

javascript - 如何将关联数组连接到字符串中

python-3.x - 在亚马逊 sns 中在交易和促销短信之间切换

python - NLTK Sentence Tokenizer,自定义句子启动器