计算每行的字数

新手上路,请多包涵

我正在尝试在 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')

原文由 LMGagne 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 473
2 个回答

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()]

原文由 cs95 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是一种使用 .apply() 的方法:

 df['number_of_words'] = df.col.apply(lambda x: len(x.split()))

例子

鉴于此 df

 >>> df
                    col
0  This is one sentence
1           and another

应用后 .apply()

 df['number_of_words'] = df.col.apply(lambda x: len(x.split()))

>>> df
                    col  number_of_words
0  This is one sentence                4
1           and another                2

注意:正如评论和 此答案 中所指出的, .apply 不一定是最快的方法。如果速度很重要,最好使用 @cᴏʟᴅsᴘᴇᴇᴅ的 方法之一。

原文由 sacuL 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题