我试图在DataFrame中创建一个新列,其中包含相应行的单词计数。我正在寻找单词的总数,而不是每个不同单词的频率。我以为会有一个简单/快速的方法来完成这个常见的任务,但在谷歌上搜索并阅读了一些SO帖子之后(1,2,3,4)我被卡住了。我已经尝试了链接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')
6条答案
按热度按时间nwnhqdif1#
str.split
+str.len
str.len
可以很好地处理任何非数字列。str.count
如果你的单词是单空格分隔的,你可以简单地把空格数加1。
列表解析
这比你想象的要快!
olqngx592#
下面是使用
.apply()
的方法:示例
假设
df
:应用
.apply()
后注意:正如评论和this answer中指出的,
.apply
不一定是最快的方法,如果速度很重要,最好使用@c s的方法。cxfofazt3#
这是使用
pd.Series.str.split
和pd.Series.map
的一种方法:上面假设
df['col']
是一系列字符串。示例:
omtl5h9j4#
使用来自cold的
list
和map
数据wtzytmuj5#
你也可以
map
split
和len
方法到DataFrame列中的字符串:这里给出了一些初步的基准测试答案。
map
似乎在非常大的系列上做得很好:w80xi6nr6#
你可以在Pandas内置的str.count()方法中使用一个简单的正则表达式:
\w
字符类匹配任何单词字符,包括任何字母、数字或下划线。它等效于字符范围[A-Za-z 0 -9_]。+
符号表示1次或无限次重复。如果您希望单词仅由字母符号组成,请使用以下正则表达式: