字数p

2024-07-08 07:06:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图在数据框中创建一个新列,其中包含相应行的单词count。我要看的是单词的总数,而不是每个单词的频率。我以为有一个简单/快速的方法来完成这项常见的任务,但在四处搜索并阅读了一些这样的帖子(1234)之后,我陷入了困境。我已经尝试了linked 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')

Tags: 数据nodflenobjectcountattributecol
3条回答

这是使用^{}^{}的一种方法:

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

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

以下是使用.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

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

相关问题 更多 >

    热门问题