计算 Pandas 数据框中的单个单词

Count individual words in Pandas data frame

我正在尝试计算数据框中一列中的单个单词。看起来像这样。实际上,文本是推文。

text
this is some text that I want to count
That's all I wan't
It is unicode text

所以我从其他 Whosebug 问题中发现我可以使用以下内容:

Count distinct words from a Pandas Data Frame

我的 df 称为结果,这是我的代码:

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

text的dtype是object,据我了解对于unicode文本数据是正确的。

出现此问题是因为您的系列 (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'

最后我使用了以下代码:

pd.set_option('display.max_rows', 100)
words = pd.Series(' '.join(result['text'].astype(str)).lower().split(" ")).value_counts()[:100]
words

然而,这个问题被 Anand S Kumar 解决了。