在 Pandas 数据框中统计每个单词的出现次数

5
我正在尝试计算数据框中一列中每个单词的数量。数据看起来是这样的。实际上,这些文本是推特。
text
this is some text that I want to count
That's all I wan't
It is unicode text

我在其他stackoverflow的问题中发现,我可以使用以下方法:

从Pandas数据框架中的句子中计算出最常见的100个单词

从Pandas数据框架中计算不同的单词数量

我的数据框架称为result,以下是我的代码:

from collections import Counter
result2 = Counter(" ".join(result['text'].values.tolist()).split(" ")).items()
result2

我收到以下错误提示:
TypeError                                 Traceback (most recent call last)
<ipython-input-6-2f018a9f912d> in <module>()
      1 from collections import Counter
----> 2 result2 = Counter(" ".join(result['text'].values.tolist()).split(" ")).items()
      3 result2
TypeError: sequence item 25831: expected str instance, float found

文本的数据类型是对象(object),据我理解这对于Unicode文本数据是正确的。


显然你的数据框中有浮点数值,你想对它们做什么?你也想将它们计算在内吗? - Anand S Kumar
由于这些文本应该都是推文,我也想对它们进行计数。如果此列还包含浮点值,那是否意味着我收集了一些只是数字的推文?(让我很好奇哪些是浮点数) - Lam
是的,那是可能的。 - Anand S Kumar
2个回答

8
问题出现的原因是你的系列中(result['text'])的一些值是float类型。如果你想在' '.join()期间同时考虑它们,那么在将它们传递给str.join()之前,你需要将浮点数转换为字符串。
你可以使用Series.astype()将所有值转换为字符串。此外,你真的不需要使用.tolist(),你也可以直接将系列提供给str.join()。例如:
result2 = Counter(" ".join(result['text'].astype(str)).split(" ")).items()

演示 -

In [60]: df = pd.DataFrame([['blah'],['asd'],[10.1]],columns=['A'])

In [61]: df
Out[61]:
      A
0  blah
1   asd
2  10.1

In [62]: ' '.join(df['A'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-62-77e78c2ee142> in <module>()
----> 1 ' '.join(df['A'])

TypeError: sequence item 2: expected str instance, float found

In [63]: ' '.join(df['A'].astype(str))
Out[63]: 'blah asd 10.1'

谢谢,看起来这个方法可行。现在输出是一个字典,将其移回到 pandas 数据框中是否合理,或者只需在数据框内继续操作? - Lam
取决于你打算做什么工作。但我猜如果你打算进行某种分析,数据框架会更快。 - Anand S Kumar
通用问题的通用回答:D 当我有具体问题时,我会提出新的问题。感谢您的帮助! - Lam

2
最终我选择了以下代码:
pd.set_option('display.max_rows', 100)
words = pd.Series(' '.join(result['text'].astype(str)).lower().split(" ")).value_counts()[:100]
words

问题已被Anand S Kumar解决。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接