我正在尝试在DataFrame中创建一个新列,其中包含相应行的单词计数。我在找单词的总数,而不是每个不同单词的频率。我以为会有一种简单/快速的方式来完成这个常见的任务,但是在谷歌上搜索并阅读了少量的SO帖子(1、2、3、4)之后,我被困住了。我已经尝试过在链接所以帖子中提出的解决方案,但是得到了很多属性错误。
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')
发布于 2018-04-23 07:43:07
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()]
发布于 2018-04-23 07:43:07
下面是一种使用.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
Note:正如注释和this answer中指出的那样,.apply
不一定是最快的方法。如果速度很重要,最好使用@cᴏʟᴅsᴘᴇᴇᴅ's方法之一。
发布于 2018-04-23 07:40:35
这是一种使用pd.Series.str.split
和pd.Series.map
的方法
df['word_count'] = df['col'].str.split().map(len)
以上假设df['col']
是一系列字符串。
示例:
df = pd.DataFrame({'col': ['This is an example', 'This is another', 'A third']})
df['word_count'] = df['col'].str.split().map(len)
print(df)
# col word_count
# 0 This is an example 4
# 1 This is another 3
# 2 A third 2
https://stackoverflow.com/questions/49984905
复制相似问题