我必须从数据帧的第df['messages']
行中统计最多出现的单词数。它有许多列,所以我将所有行格式化并存储为单个字符串(单词按空格连接),存储在一个variabelall_words
中all_words
所有单词都用空格分隔。但当我试着数一数最常用的单词时,它显示了我最常用的字母表。
我的数据格式如下:
0 abc de fghi klm
1 qwe sd fd s dsdd sswd??
3 ded fsf sfsdc wfecew wcw.
这是我的代码片段。
from collections import Counter
all_words = ' '
for msg in df['messages'].values:
words = str(msg).lower()
all_words = all_words + str(words) + ' '
count = Counter(all_words)
count.most_common(3)
这是它的输出:
[(' ', 5260), ('a', 2919), ('h', 1557)]
我还尝试使用df['messages'].value_counts()
。但它返回使用最多的行(整个句子)而不是单词。
比如:
asad adas asda 10
asaa as awe 3
wedxew dqwed 1
请告诉我哪里错了,或者建议其他可行的方法
计数器对传递给它的内容进行迭代。如果您向它传递一个字符串,它将进行迭代,因为它有个字符(这就是它的计数)。如果您向它传递一个列表(其中每个列表都是一个单词),它将按单词计数
所以,你应该这样做:
相关问题 更多 >
编程相关推荐