我有这样一个DF:
Doc_ID Text
1 hi hi hi
2 hello hello1 hello
3 hey hallo
我想计算文本列中的单词数,并将其存储在名为(topXwords)的新列中。 所需输出:
Doc_ID Text topXwords
1 hi hi hi hi:3
2 hello hello1 hello hello:2, hello1:1
3 hey hallo hey:1, hallo:1
我试过什么?
我尝试将文本列转换为列表:
df["topXwords"] = df["Text"].str.split()
在那之后,我试着在列表上循环,并计算列表中的所有项目。对于1列表,它可以工作,但无法将其存储为新列:
import collections
df["topXwords1"]= collections.Counter(df["topXwords"])
TypeError: unhashable type: 'list'
This fails, but it works in this example:
xxx = ["a","a","b"]
counter = collections.Counter(xxx)
counter
Out[43]: Counter({'a': 2, 'b': 1})
**我使用counter,因为它只在一个示例中起作用。理想情况下,我想调整顶部关键字的数量。**
非常感谢您的帮助
具有
pd.Series.value_counts
功能:使用apply:
输出
如果只想包含前x个单词,请执行以下操作(在本例中x=1):
输出
相关问题 更多 >
编程相关推荐